mercredi 19 octobre 2016

Constructors with objects as parameters

Suppose I have a class as follows:

class A{
    int x ; 
    A( int i ){
        x = i ; 
    }
}

And I have another class B which has an instance of class A as an member object.

class B{
    int y ; 
    A obj_a ; 
    B( int j , A a ){
        y = j ; 
        obj_a = a ; 
    }
}

When I do the following :

int main(){
        A obj1( 1 ) ; // obj.x has value 1
        B obj2( 2 , obj1 ) ; 
    }

The 2nd line throws an error saying no function call of the form A::A(). I know this means that a default style constructor is missing , but why do I need this ? obj1 is created using the defined constructor so that isn't an issue.

My current line of thought is that A a and obj_a = a would invoke the copy constructor which is implicitly defined.

Aucun commentaire:

Enregistrer un commentaire