Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to the class constructor in a declaration of another class

I've got sth like that:

#include <iostream>
using namespace std;

class FirstClass
{
    public:
        FirstClass(int _vx) : vx(_vx) {}
        int x () {return vx;}
    private:
        int vx;
};

It's pretty obvious, that I have to write:

int main ()
{
    FirstClass Object1(666);
    cout << Object1.x();
    return 0;
}

And everything is ok. But problem is, when I want to have this in another class:

#include <iostream>
using namespace std;

class FirstClass
{
    public:
        FirstClass(int _vx) : vx(_vx) {}
        int x () {return vx;}
    private:
        int vx;
};

class SecondClass
{
    public:
        FirstClass Member1(666);
};

int main ()
{
    SecondClass Object2;
    cout << Object2.Member1.x();
    return 0;
}

I can't even compile it. So, my question is: how can I pass arguments to constructor of FirstClass in a declaration of SecondClass?

Thanks in advance.

like image 396
drevv Avatar asked Jul 24 '11 13:07

drevv


1 Answers

You've got to pass the initialization value to FirstClass in the constructor of SecondClass, like this:

class SecondClass:
   {
   public:
      SecondClass() : Member1(666) {}
      Firstclass Member1;
   };
like image 59
Patrick Avatar answered Nov 10 '22 00:11

Patrick