Reputation: 35
Is it possible to forward declare a class and then use its member funcions? I'm trying to do this:
class Second;
class First{
private:
int x=0;
public:
void move(Second* s,int i){
s->setLine(i);
s->called(true);
}
int getX(){return x;}
}
class Second{
private:
int line=2;
bool cal=false;
public:
void setLine(int l){line = l;}
void called(bool b){cal=b}
bool interact(First* f){
if ((f->getX())>3)
return true;
else
return false;
}
}
My actual problem is a bit more complex and the funcions do more stuff but what I'm trying to do is have these two classes use eachother funcions and have them interact this way. Does anyone know if there is a way to do this?
Upvotes: 0
Views: 256
Reputation: 206607
Is it possible to forward declare a class and then use its member functions?
No, it is not. You cannot access any member of a forward declared class, variables, functions, enums, nested types, etc., until the class is defined.
You need to move the implementation of the function that calls the member function of the forward declared class after the forward declared class is defined.
class Second;
class First{
private:
int x=0;
public:
void move(Second* s,int i); // Don't define it here.
int getX(){return x;}
};
class Second{
...
};
// Define the function now.
void First::move(Second* s,int i){
s->setLine(i);
s->called(true);
}
Upvotes: 3
Reputation: 1725
The following will do the trick for you, but it's better to separate declaration and implementation.
class Second;
class First{
private:
int x=0;
public:
void move(Second* s,int i); //<- move implementation after Second's declaration
int getX(){return x;}
}
class Second{
private:
int line=2;
bool cal=false;
public:
void setLine(int l){line = l;}
void called(bool b){cal=b}
bool interact(First* f){
if ((f->getX())>3)
return true;
else
return false;
}
};
void First::move(Second* s,int i){
s->setLine(i);
s->called(true);
}
Upvotes: 1
Reputation: 18964
You can put the definition of First::move
outside the class, after the definition of Second
. Only the declaration needs to appear inside the definition of First
.
You could in fact put the definition of First::move
in a .cpp file and not in any header.
Upvotes: 1