C++ declare derived class object inside of if-else and use it outside

Viewed 400

I have a (parent) class named Alma with the (virtual) function Getwidth() and two derived class of Alma, named Birs (with the special function Getheight()) and Citrom (with the special function Getdepth()). I want to declare an object - named Attila - which type is Birs or Citrom depending on a bool. Later, I want to use the common function Getwidth() and also the special functions (depending the bool mentioned).

My (not working) code:

/*...*/
/*Classes*/
class Alma{
  public: virtual int Getwidth() = 0;
  /*ect...*/
}

class Birs: public Alma{
  int Getwidth(){return 1;}
  public: int Getheight(){return 2;}
  /*ect...*/
}

class Citrom: public Alma{
  int Getwidth(){return 3;}
  public: int Getdepth(){return 4;}
  /*ect...*/
}
/*...*/
/*Using them*/
void Useobjects(){

/*Create object depending on bool*/
  if(b00lvar){
    Birs Andor();
    std::cout<<Andor.Getwidth()<<" "<<Andor.Getheight()<<std::endl;
  }else{
    Citrom Andor();
    std::cout<<Andor.Getwidth()<<" "<<Andor.Getdepth()<<std::endl;
  }

/*Using the common part of object*/  
  std::cout<<Andor.Getwidth()<<std::endl;

/*Using the special part of object*/
  if(b00lvar){
    std::cout<<Andor.Getheight()<<std::endl;
  }else{
    std::cout<<Andor.Getdepth()<<std::endl;
  } 

/*ect...*/
}
6 Answers
Related