tags:

views:

70

answers:

3

Hello. I'm trying to instantiate a class within 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", is my attempt at containing the inner within the outer, however, when I compile, i get an error that there is no matching function for call to Inner::Inner(). What have I done wrong?

Thanks.

+5  A: 
sbi
Thanks! I managed to figure it out from this.
Ink-Jet
+1  A: 

Since Inner has no default constructor, you need to initialize it explicitly. The way to do this, as @sbi pointed out, is using the initialization list in the constructor.

Péter Török
A: 

You could also add a constructor to Inner that takes no argument. It's implicitly trying to call it since you're not explicitly initializing in in Outer. If in were a pointer (Inner *in), then it would work.

Basically if you write

Foo f;

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

Christopher Bertels
But then it would first default-initialize the object just to immediately overriding that value with the assignment operator. Sorry, but IMO that's bad advice, better use initialization lists to specify the right constructor. -1 from me.
sbi
oh, that's true. just wanted to point out that this is also possible (and in general terms might be needed).
Christopher Bertels