#include <iostream>
usingnamespace std;
class A;
class B;
class A{
public:
A(): b(5){
temp=2;
}
int get_temp(){
return temp;
}
private:
int temp;
B b;
};
class B{
public:
B(int x){
i = x;
}
int get_i(){
return i;
}
void ii(int x){
i = x;
}
private:
int i;
};
int main(){
A a;
cout<<a.get_temp();
}
1.) It's bad practice to include multiple classes into one file.
2.) What is this used for?
3.) What is your logic behind wanting to do it specifically this way?
4.) I'm tired. Good night.
How can I resolve this matter with the same order of classes?
As Peter has said, as class A has a member of class B then the order of definition must be reversed.
If you do for some reason require absolutely that class A is defined before class B in your file, then you can use a pointer to class B in class A instead. But the methods of class A that use B will still need to be defined after class B is defined.
(The reasons that the definition of a class member which is another class must be know beforehand is that the compiler needs to know its size and layout so it can work out the overall layout of the class you're defining. If you use a pointer to the other class instead this is not a problem as the size of a pointer is fixed for a given architecture.)
#include <iostream>
usingnamespace std;
class A;
class B;
class A{
public:
A(); // implementation must come after B is defined
~A(); // now need destructor
int get_temp(){
return temp;
}
int get_b_result(); // new method that uses B
private:
int temp;
B* pb; // now a pointer to class B
};
class B{
public:
B(int x) : i(x) { // prefer to use init list
//i = x;
}
int get_i(){
return i;
}
void ii(int x){
i = x;
}
private:
int i;
};
A::A(): temp(2), pb(new B(5)) { // prefer to use init list (note B now new-ed)
//temp=2;
}
A::~A() {
delete pb;
}
int A::get_b_result() {
return pb->get_i();
}
int main(){
A a;
cout<<"temp = "<<a.get_temp()<<"\n";
cout<<"b_result = "<<a.get_b_result()<<"\n";
return 0;
}
Andy
PS Regarding
1.) It's bad practice to include multiple classes into one file.
It's bad practice to include multiple classes into one file
I think this only applies if the classes are used for very different things (could be classed into modules) or if you've got a really big project you might put one class per header file to reduce compile times as if you edit one class only the one needs to be recompiled, but I'm not sure about that.