struct A{
public:
A(int value) : x(value) {};
private:
int x;
};
A a = A(10);
a.x;
input_line_4:3:3: error: 'x' is a private member of 'A' a.x; ^ input_line_3:10:5: note: declared private here int x; ^
struct B{
public:
B(int value) : x(value) {};
int getX() {return x;};
void setX(int value) {x = value;};
private:
int x;
};
B a = B(10);
a.setX(11);
a.getX();
(int) 11
#include <iostream>
#include <vector>
static size_t count;
class D
{
public:
D() {count++;};
~D() {count--;};
};
D* d1 = new D();
std::cout << count << std::endl;
D* d2 = new D();
std::cout << count << std::endl;
delete d1;
std::cout << count << std::endl;
1 2 1
(std::basic_ostream<char, std::char_traits<char> >::__ostream_type &) @0x7efc9eef9500
#include <string>
class Person{
public:
std::string name;
Person () {};
Person (std::string name) : name(name){};
};
class Student : public Person {
public:
int id;
Student (std::string name, int id) : Person(name), id(id) {};
};
Student s1 = Student("Pet the Cat",123456);
s1.id;
(int) 123456
s1.name;
(std::string &) "Pet the Cat"
Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.
class Person2{
protected:
std::string name;
public:
Person2 () {};
};
class Student2 : public Person2 {
public:
Student2 (std::string name, int id ) {
name = name;
id = id;
};
};
In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not apply to "friends".
struct E {
private:
int value;
public:
E(int in) : value(in) {};
friend std::ostream &operator<<( std::ostream &output, const E &e );
};
extern "C++"
std::ostream &operator<<( std::ostream &output, const E &e ){
output << e.value << std::endl;
return output;
};