Instantiating a class within a class

Posted by Ink-Jet on Stack Overflow See other posts from Stack Overflow or by Ink-Jet
Published on 2010-05-30T11:49:53Z Indexed on 2010/05/30 11:52 UTC
Read the original article Hit count: 156

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about class