Home > Enterprise >  Get properties of derived class from base class argument
Get properties of derived class from base class argument

Time:12-02

I not sure how to ask this but basically i pass a base class as an parameter and if the argument is a derived class from the base class i want to be able to access properties only in the derived class

class A{
public:
  bool isB = false; 
  int x = 69;
}
class B : public A{
public:
  bool isB = true;
  int y = 420;
}
void Print(A c){
  if (c.isB)
    cout << c.y << endl; //this will error as the class A has no y even though i will pass class B as an argument
  else
    cout << c.x << endl;
}

A a;
B b;

Print(a);
Print(b);

CodePudding user response:

My recommendation is that you use polymorphism by creating a virtual "print" function that your global Print function calls:

class A
{
    int x = 69;

public:
    virtual ~A() = default;  // Needed for polymorphic classes

    virtual void print(std::ostream& out) const
    {
        out << x;
    }
};

class B : public A
{
    int y = 420;

public:
    void print(std::ostream& out) const override
    {
        out << y;
    }
};

void Print(A const& o)
{
    o.print(std::cout);
    std::cout << std::endl;
}

int main()
{
    A a;
    B b;

    Print(a);
    Print(b);
}

CodePudding user response:

You need to define a virtual function "bool amIaB()" in both base and derived class that returns "isB".

  • Related