Reputation: 18604
I'm trying to invoke a constructor from out of another class. But unfortunately I get this error:
Fun2 was not declared in this scope
This is my code:
class Fun1 {
public:
Fun1 () {
Fun2("Message");
}
};
class Fun2 {
public:
Fun2 (std::string s) {
std::cout << s;
}
};
int main()
}
How can I send my "message" to the constructor of the other class?
Upvotes: 0
Views: 193
Reputation: 290
Fun2 must be declared first if you use it in Fun1:
class Fun2 {
public:
Fun2 (std::string s) {
std::cout << s;
}
};
class Fun1 {
public:
Fun1 () {
Fun2("Message");
}
};
int main()
}
Upvotes: 2
Reputation: 110698
C++ is typically compiled from top to bottom. Since you attempt to use Fun2
before you have defined it, the compiler is complaining. Instead, you can simply define your Fun2
class first:
class Fun2 {
public:
Fun2 (std::string s) {
std::cout << s;
}
};
class Fun1 {
public:
Fun1 () {
Fun2("Message");
}
};
Now when the compiler sees you use the identifier Fun2
, it knows what it corresponds to because it has already seen the definition.
There are occasions when the compiler actually parses code in multiple passes and in these places identifiers can be declared after they are used (members, for example).
Upvotes: 2
Reputation: 10719
Fun2 is not defined at the time you define Fun1.
Try a forward declartion.
class Fun2;
class Fun 1 {
... class definition
}
class Fun2 {
.... class definition
}
Upvotes: 1