PrevUpHomeNext

day-06: private protected public


cpp object-oriented encapsulation: private protected public

cpp/c++ object-oriented encapsulation: private protected public

You have already saw the public usage case from previous articles, private and protected have the same way with public .

private

protected

public

-> derived class: inheritance

Inheritance will be explained in the next article.

See example

Save as brick.cpp

#include <iostream>

class brick
{
private:
	std::string name1;
protected:
	std::string name2;
public:
	std::string name3;
public:
	void set_names(std::string n1, std::string n2, std::string n3)
	{
	// access name1, name2, name3 from the inside of the class.
		name1 = n1;
		name2 = n2;
		name3 = n3;
	}
	std::string get_name1()
	{
		return name1;
	}
};

int main()
{
	auto a_brick = brick{};

	a_brick.set_names("A", "b", "c");

	std::string nm1 = a_brick.get_name1();

	std::cout << nm1 << std::endl;

	// access attribute name3 from the outside of the class.
	a_brick.name3 = "D";

	std::cout << a_brick.name3 << std::endl;
}

Compile and run:

$ g++ brick.cpp -std=c++23 -o brick
$ ./brick
A
D
[Note] Note

name1 can be accessed from the inside of the class brick only, because it is private .

name2 can be accessed from the inside of the class brick, and from the inside of derived class of brick, because it is protected, but can not be accessed from the outside of the class .

name3, set_names, get_name1 can be accessed from the inside of the class brick, the inside of the derived class of brick, and outside of the class, because they are public .

Inheritance or (derived class) will be explained in the next article.

Last

Do not feel stress, this article only has three points:

private

protected

public

Written on Aug 04, 2024

Back to index

Index

cpp/c++

c++ std::exception:

std::cout.write(err.data(), err.size());

std::cout << std::endl;

caught:

  ===================================
  #  The c++ programming language.  #
  #                                 #
  #  Join c++ Discord: yZcauUAUyC   #
  #  Deck                           #
  ===================================

Home: cppfx.xyz

K


PrevUpHomeNext