Structure of code¶

  • Structs
    • Access specifiers
    • Static functions and members
    • Inheritance
  • Namespaces
  • Header and libraries

Access specifiers¶

In [1]:
struct A{

public:

A(int value) : x(value) {};


private:

int x;

};
Out[1]:

In [2]:
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;
    ^

Adding access methods¶

In [3]:
struct B{

public:

B(int value) : x(value) {};

int getX() {return x;};

void setX(int value) {x = value;};

private:

int x;

};
Out[3]:

In [4]:
B a = B(10);
a.setX(11);
a.getX();
Out[4]:
(int) 11

Static functions and members¶

In [5]:
#include <iostream>
#include <vector>
Out[5]:

In [6]:
static size_t count;

class D
{

public: 

D() {count++;};

~D() {count--;};

};
Out[6]:

In [7]:
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
Out[7]:
(std::basic_ostream<char, std::char_traits<char> >::__ostream_type &) @0x7efc9eef9500

Inheritence¶

In [8]:
#include <string>
Out[8]:

In [9]:
class Person{

public:

std::string name;

Person () {};

Person (std::string name) : name(name){};

};
Out[9]:

In [10]:
class Student : public Person {

public: 

int id;

Student (std::string name, int id) : Person(name), id(id) {};

};
Out[10]:

In [11]:
Student s1 = Student("Pet the Cat",123456);
Out[11]:

In [12]:
s1.id;
Out[12]:
(int) 123456
In [13]:
s1.name;
Out[13]:
(std::string &) "Pet the Cat"

Protected¶

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.

In [14]:
class Person2{

protected:

std::string name;

public:

Person2 () {};

};
Out[14]:

In [15]:
class Student2 : public Person2 {

public:
 
Student2 (std::string name, int id ) {

name = name;
id = id;

};

};
Out[15]:

Friend¶

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".

In [16]:
struct E {

private:

int value;

public:

E(int in) : value(in) {};

friend std::ostream &operator<<( std::ostream &output, const E &e ); 

};
Out[16]:

In [17]:
extern "C++"
std::ostream &operator<<( std::ostream &output, const E &e ){ 

output << e.value << std::endl; 
return output; 

};
Out[17]: