Creating an instance of a class inside a class

I am trying to create an instance of a class inside a class so that the outer class contains the inner class.

This is my code:

#include <iostream>
#include <string>

class Inner {
    private: 
        std::string message;

    public:
        Inner(std::string m);
        void print() const;
};

Inner::Inner(std::string m) {
    message = m;
}

void Inner::print() const {
    std::cout << message << std::endl;
    std::cout << message << std::endl;
}

class Outer {
    private:
        std::string message;
        Inner in;

    public:
        Outer(std::string m);
        void print() const;
};

Outer::Outer(std::string m) {
    message = m;
}

void Outer::print() const {
    std::cout << message << std::endl;
}

int main() {
    Outer out("Hello world.");
    out.print();

    return 0;
}

"Inner in", I try to hide the inner inner outer, however, when I compile, I get an error that there is no corresponding function to call Inner :: Inner (). What did I do wrong?

Thank.

0
source share
3 answers

To initialize class members, you need to use initialization lists:

Inner::Inner(const std::string& m)
  : message(m)
{
}

Outer::Outer(const std::string& m)
  : in(m)
{
}

(Note that I passed the strings for the constlink, which is better than passing them by value. See this answer on how to pass arguments to a function.)

, .

, . , . .
Inner ( ), , , .


: : , , :

Outer::Outer(const std::string& m) : in1(m), in2(m), in3() {}

, , , . , . , :

class outer {
  public:
    outer(const inner& in) 
     : in_(in), rin_(in_) // depends on proper declaration order of in_ and rin_
    {}
  private:
    inner in_;   // declaration order matters here!1
    inner& rin_; // (see constructor for details)
};

, , . , , .


, BTW, . .

+6

Inner , . , @sbi, .

+1

You can also add a constructor to Inner, which takes no arguments. It implicitly tries to call it, since you are not explicitly initializing into Outer. If there inwas a pointer ( Inner *in), it would work.

Basically, if you write

Foo f;

in C ++, it will call the default constructor ( Foo::Foo()).

-1
source

All Articles