How to initialize a constructor of a nested class in C ++

I'm having problems initializing the constructor of nested classes.

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 am getting is:

 fun.cpp:21:30: error: no match for call to '(a::b)' 
+4
source share
4 answers

You probably want something like:

 class a { public: a():title(b("")) {} //.... }; 

This is because title already a member of a , however there is no default constructor for it. Either write the default constructor, or initialize it in the initialization list.

+6
source

You must either make your data member a pointer, or you can only call the data element constructor from the initialization list of the constructor of the class of which it is a member (in this case a )

+1
source

It:

 document.title("Hello World"); 

is not "initialization of a nested class"; he is trying to call operator() on an object.

A nested object is already initialized when creating a document . Also, that is not the case because you did not create a default constructor.

+1
source

So what do you have here:

 class A { B title; } 

Without a constructor definition for class A (as shown by Lucian Grigore), the title will be initialized as: B title();

You can work like this:

 A::A():title(B("Hello world")) // Or by adding non parametric constructor: class B { B(){ } B( const char *str){ } } 

The object header (in the document) is already initialized, and you can no longer call the constructor, but you can still use the syntax: document.title(...) by declaring and defining operator() , but it will no longer be a constructor:

 class B { const B& operator()(const char *str){ cout << str; return *this; } } 
0
source

Source: https://habr.com/ru/post/1395003/


All Articles