2

I'm new to C++, but I have previous programming experience in PHP and C# (OOP). What I have is: two classes one of which has a private property with the type of the other class. Source:

class Foo
{
    public:
        Foo(int n)
        {

        }
};

class Bar
{
    private:
        Foo foo;

    public:
        Bar()
        {
            this->foo = Foo(10);
        }
};

Bar bars[123];

What I'm trying to do is declare a property of Foo with a constructor in Bar. Unfortunately, the way I did it doesn't work. It gives a series of errors e.g.

no matching function for call to 'Foo::Foo()'

How do I get it working? Thanks for your reply.

user3022069
  • 377
  • 1
  • 4
  • 13

1 Answers1

4

You need to initialize Foo properly in a member initialization list, like so:

class Bar
{
    private:
        Foo foo;

    public:
        Bar() :
            foo(10)
        {}
};

Otherwise, what happens is that the compiler first tries to initialize this->foo with a default constructor before getting into the body of your constructor. Since Foo doesn't have one, it fails to compile.

Yam Marcovic
  • 7,953
  • 1
  • 28
  • 38