Virtual function and class inhertance

I'm confused about the code below:
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
29
30
31
32
33
class A
{
public:
	A() { bar(); };
	virtual ~A() { bar(); };
	virtual void foo() {
		cout << "1";
		return;
	}

	virtual void bar() {
		foo();
		return;
	}
};

class B : public A
{
public:
	B() { bar(); };
	virtual ~B() { bar(); };
	virtual void foo() {
		cout << "2";
		return;
	}
};

int main()
{
	B b;
	b.bar();
	return 1;
}

The output of the code above is "12221".
The code executes as below:
1. bar() in constructor of A(actually it is called by constructor of B);->"1"
2. bar() in constructor of B;->"2"
3. code B.bar();->"2"
4. bar() in destructor of B;->"2"
5. bar() in destructor of A;->"1"

Why constructor of A executes when instantiate an object of class B(In case of constructor of class B is defined).
Last edited on
When a virtual function is called directly or indirectly from a constructor or from a destructor ..., and the object to which the call applies is the object under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class. In other words, during construction or destruction, the more-derived classes do not exist.
https://en.cppreference.com/w/cpp/language/virtual#During_construction_and_destruction
Thanks for your reply that helps me a lot.
However, I am still confused about why the constructor of A should be executed before constructing b, which is an object of B. In other words, is it possible to execute constructor of class B only?
Simply, B class is derived from A class. So before B class is 'created' the base class A has to be 'created'. So no, for a derived class the base class is always first constructed. The base class can have multiple constructors and the derived class can explicitly call any available.

Consider (without using virtual):

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
#include <iostream>

struct A {
	int a {};

	A() {}
	A(int a_) : a(a_) {}
};

struct B : public A {
	int b {};

	B() {}
	B(int a, int b_) : A(a), b(b_) {}
};

int main() {
	A a1(10);
	B b1(20, 30);
	B b2;

	std::cout << "a1: " << a1.a << '\n';
	std::cout << "b1: " << b1.a << "  " << b1.b << '\n';
	std::cout << "b2: " << b2.a << "  " << b2.b << '\n';
}


B effectively has 2 members a (from class A as that is what B is derived from) and b which is only for class B.

But from b1 and b2 you can also access a as B is derived from A and when B is created A is also created first so that B also has the member a. If A wasn't created first before B then B wouldn't have access to a from A.
Last edited on
Truly grateful for all your help.
I get it.
Topic archived. No new replies allowed.