objects assignment

Nov 2, 2019 at 8:10am
I am facing a problem with this code
I don't know why the output is
A's constructor called
B's constructor called
A's constructor called
I thought it will print
"A's constructor called" another time for t object but assignment stopped that
why did assignment stop it ?

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
#include <iostream>
using namespace std;

class A
{

public:
    int x = 3;
	A() { cout << "A's constructor called" << endl; }
};

class B
{
public:
	A a;
public:
	B() { cout << "B's constructor called" << endl; }
	A getA() { return a; }
};


int main()
{
	B b1;
	A tt;
	A t = b1.getA();
	return 0;
}
Nov 2, 2019 at 8:18am
Because it's no longer calling the default constructor, doing A a = getA(); is calling the copy constructor to initialize a.
Nov 2, 2019 at 9:23am
thank you
Topic archived. No new replies allowed.