+ 1

Instantiation: Object written in main() vs in class

Below, the former code fails while the latter successfully compiles. The difference is where the object is placed. Why doesn't the former one work? Is it because instantiation cannot place until the corresponding class has been declared first? class A { public: A() { cout <<"a";} ~A() { cout <<"b";} B b; }; class B{ public: B() { cout <<"c";} ~B() { cout <<"d";} }; int main() { A a; } ==================== class A { public: A() { cout <<"a";} ~A() { cout <<"b";} }; class B{ public: B() { cout <<"c";} ~B() { cout <<"d";} A a; }; int main() { B b; }

11th Aug 2020, 9:01 AM
Solus
Solus - avatar
1 Respuesta
+ 1
That's because the class definition is not known yet when you write B b. You may achieve this by using forward declaration of classes . https://code.sololearn.com/c7w5dhXEnGtz/?ref=app
11th Aug 2020, 9:47 AM
Hima
Hima - avatar