user1164199
user1164199

Reputation: 379

Calling C++ constructor issue

I am seriously misunderstanding c++ constructors. In the code shown below, I am trying to inialize aVar in MyClass1. The code generates the following errors (also shown in the code):

(1) "aVar2" has already been declared in the current scope
(2) reference variable "var" requires an initializer

Could someone point me in the right direction.

Thanks.

class Myclass1
{
public:
    Myclass1(int * var1);
    Myclass1(void);

private:
    int * aVar;
};

class Myclass2
{
public:
    Myclass2(int * var2);

private:
    Myclass1 myclass1;

};

class Myclass3
{
public:
    Myclass3(void);

private:
    Myclass2 myclass2;
    int var;
};

Myclass1::Myclass1(int * aVar1)
{

    aVar = aVar1;
}

Myclass2::Myclass2(int * aVar2)
{
   //ERROR: "aVar2" has already been declared in the current scope  
    Myclass1(aVar2);
}

Myclass3::Myclass3(void)
{
    var = 2;

    //ERROR: reference variable "var" requires an initializer
    Myclass2(&var);
}

int main(void)
{

    Myclass3 myFinalClass;
    return 0;
}

Upvotes: 0

Views: 88

Answers (2)

legends2k
legends2k

Reputation: 32994

Myclass1(aVar2);

isn't right, since the member variable name is myclass1 and also you've to assign to it like this: myclass1 = aVar2. Here the compiler thinks that you're just trying to create a new Myclass1 object with the same name as the parameter. Here's what you need:

Myclass2::Myclass2(int * aVar2) : myclass1(aVar2) { }

Myclass3::Myclass3() : myclass2(&var) { }

Know that initializer lists are always better than initializing the members in the constructor body; see the C++ FAQ on this. Apart from giving a uniform syntax, it may be faster too. So your Myclass1 constructor would be better in this form:

Myclass1::Myclass1(int * aVar1) : aVar(aVar1) { }

Upvotes: 1

AnatolyS
AnatolyS

Reputation: 4319

Myclass1(aVar2) is not a constructor call, it is a definition of the aVar2 object.

Upvotes: 0

Related Questions