I have 3 question about C++. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

I have 3 question about C++.

1-class A{ public://Can I declare my constructor and destructor with other modifiers? For example, private or protected. A(){cout<<a} ~A(){cout<<b} }; class B{ public: B(){cout<<c} ~B(){cout<<d} A a; }; void main() { B b; } What I think is that the output must be "cabd", because first B's constructor works and after that the A's constructor works and then A's destructor work then B's destructor works. But when I look the answer, it says "acbd". I am confused. Thanks for answers.

5th Aug 2017, 9:59 AM
Yusuf
Yusuf - avatar
2 Answers
+ 6
Yes, you may, But then , you won't be able to create new objects directly. In protected, you may still inherit the class, but in private, the class becomes non usable,unless you declare a separate public constructor that can call that constructor... Here the output is acbd as in inheritance, before creating a derived class object, a base class object must exist. (Eg - Father must exist before son). So a base class object is created for use by the derived class before calling its constructor (you may have some data initialization from base class into derived class. Similarly, in destruction process, the derived class destructor is first invoked, then the base class constructor, as the the base class object must exist till the derived class object is destroyed.
5th Aug 2017, 1:25 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
0
Banana was here
21st Aug 2017, 2:34 PM
MARCUS CASE
MARCUS CASE - avatar