+ 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; }
1 Odpowiedź
+ 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