Reputation: 2679
I am getting problems in initializing the nested class constructor.
Here is my code:
#include <iostream>
using namespace std;
class a
{
public:
class b
{
public:
b(char str[45])
{
cout<<str;
}
}title;
}document;
int main()
{
document.title("Hello World"); //Error in this line
return 0;
}
The error I get is:
fun.cpp:21:30: error: no match for call to '(a::b)'
Upvotes: 4
Views: 8484
Reputation: 21007
So what do you have here:
class A {
B title;
}
Without defining constructor for class A (as Luchian Grigore shown) title will be initialized as: B title();
You can work that around by:
A::A():title(B("Hello world"))
// Or by adding non parametric constructor:
class B {
B(){
}
B( const char *str){
}
}
Object title (in document) is already initialized and you cannot call constructor anymore, but you still may use syntax: document.title(...)
by declaring and defining operator()
but it won't be constructor anymore:
class B {
const B& operator()(const char *str){
cout << str;
return *this;
}
}
Upvotes: 0
Reputation: 272657
This:
document.title("Hello World");
is not "initializing the nested class"; it's attempting to call operator()
on the object.
The nested object is already initialised when you create document
. Except that it's not, because you've provided no default constructor.
Upvotes: 1
Reputation: 258618
You probably want something like:
class a
{
public:
a():title(b("")) {}
//....
};
This is because title
is already a member of a
, however you don't have a default constructor for it. Either write a default constructor or initialize it in the initialization list.
Upvotes: 6
Reputation: 11908
You have to either make your data member a pointer, or you can only call the data member's constructor from the initialiser list of the construtor of the class it is a member of (in this case, a
)
Upvotes: 1