Inheritance question!

I don't understand the output at all.
How does creating an object of a class, runs the functions inside? ( sorry for bad wording here) And, how are they connected to each other?
Does class B: public A mean that class B has access to the public components of the class A?
Does class C : private B mean that class C has access to the Private components of the class B? ( which is the access to the public components of class A?)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  #include <iostream>
#include <string>
using namespace std;

class A{
public:
    A() {cout<<"A0 ";}
    A(string s) { cout << "A1 ";}
};

class B: public A{
public:
B(){ cout << "B0 ";}
B(string s) { cout<< "B1 ";}
};

class C : private B{
public:
    C() {cout<<"C0 ";}
    C(string s) {cout<<"C1 ";}
};

int main() {
    B b1;    // why does this output A0 B0 ?
    C c1;    // why does this output A0 B0 C0 ? 
    
	return 0;
}
How does creating an object of a class, runs the functions inside?

When you create an object, constructors for all of its base classes are executed, then the constructors for all of its members are executed, and finally its own constructor is executed.

When you create b1 (which is of type B, whose base class is A), the constructor for the base, A::A() is executed, then its own constructor, B::B() is executed.

When you create c1 (which is of type C, whose base is B, whose base is A), the constructor for the base of the base, A::A() is executed, then the constructor of the base, B::B() is executed, then its own constructor, C::C() is executed.

Does class B: public A mean that class B has access to the public components of the class A?

It means that public members of A are public members of B (and private members of A are private members of B)

Does class C : private B mean that class C has access to the Private components of the class B?

It means that all members of B (public and private) as well as all members of A (public and private) are private members of C.
Last edited on
Topic archived. No new replies allowed.