I have a question about inherited default constructors

1

I'm in doubt as I try to improve an OOP exercise here ..

(-) = no

I have the PAI class with two constructors (one is default). In the SON class I have two more constructors (no-default). In the definition of one of these constructors there are two conditionals that initialize the contructors of the parent class, each in a given situation.

The problem is that when I instantiate a new object of type child, with parameters to start parent constructor with parameters. It simply skips the no-default constructor and controls the default, returning an undesired value.

The simplified code is this one:

Header file -

class Pai{
int c;
public:
   int getC() //que retorna C
   Pai(){ c=100; }
   Pai(int arg){ c=arg; }
};

class Filho: public Pai{
public:
   Filho(int arg1)//esse não precisa atentar-se
   Filho(int arg1, int arg2);
};

Definition of son builder ----

Filho::Filho(int arg1){ //esse aqui é so representativo mas existe }

Filho::Filho(int arg1, arg2){
   if(arg2>0)
      Pai(arg2); //No-Default constructor 
   else{ Pai(); //Default constructor }
}

Instantiating child object -

Filho *f1 = new Filho(3, 5); 

cout << "O valor de arg2 é: " << f1->getC() << endl;

Out - > 100 (returned the default constructor)

MORE. When I instantiate directly to the parent the desired value is returned.

Why is it calling the default parent constructor without my ordering?

I have already researched this in several places and I did not find it, I hope I can find the answer here: /

    
asked by anonymous 23.12.2017 / 13:49

1 answer

1

What happens is that you are not modifying the values of your class.

Filho::Filho(int arg1, arg2){
if(arg2>0)
  Pai(arg2); //<- aqui está o erro, uma nova instancia da classe pai é criada
   else{ Pai(); //Default constructor }
}

When you do this you are actually creating a new instance of the parent class. In this case the solution would be to use a method instead of a constructor (eg setC (int c))

    
23.12.2017 / 22:39