Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make static "polymorphic" member variables

Tags:

c++

Basically what I am trying to do here is make an ID for each derived type of Shape. ( Square is 1, Circle is 2, etc.) How can I make a static member variable that has polymorphic capabilities? How would I create the getters and setters?

class Shape {
public:
    Shape() {}
    static int ID;
};

class Square : public Shape {
public:
    Square() {}

};

class Circle : public Shape {
public:
    Circle() {}

};

class Person {
public:
    int shape_type_ID
    Shape* ptr;
    Person(){}
};

int Shape::var{ 5 };

Is this a copy of this question? How to initialize `static` member polymorphically

EDIT: In my current design, each instance of Person contains a pointer ( I am not sure about the type of pointer ) that points to some Shape object. I want to restrict each Person object to only being able to reference one derived type of Shape.

E.g. Person 1’s pointer can only reference Circles, Person 2’s pointer can only reference Squares, Person 3’s pointer can only reference Triangles.

But I want 1 single Person class with 1 type of pointer ( probably Shape ). In theory that should be do-able. One of the problems is that there should be as many Person objects as there are Shape derived types (one for Square, one for Circle, one for Triangle). How do I know how many Person objects to make?

like image 791
emptyPigeon Avatar asked Feb 21 '26 15:02

emptyPigeon


2 Answers

When you want polymorphism you should use virtual methods, not static members.

class Shape {
public:
    virtual int ID(){ return 0; }
    virtual ~Shape(){}
};

class Square : public Shape {
public:
    virtual int ID() override { return 1;}
};

class Circle : public Shape {
public:
    virtual int ID() override { return 2; }
};
like image 196
463035818_is_not_a_number Avatar answered Feb 23 '26 03:02

463035818_is_not_a_number


you can do something like this if you really need to, but I suggest just making a constructor in base that accepts an id and pass it from the childs to the parent

int getNextId()
{
    static int lastId{0};
    return lastId++;
}

template<typename T>
int getDerivedId()
{
    static int id{getNextId()};
    return id;
}

struct Base {
};

struct Derived0 final : Base {
};

struct Derived1 final : Base {
};

int main() {
    return !(getDerivedId<Derived0>() == 0 && getDerivedId<Derived1>() == 1);
}
like image 25
Yamahari Avatar answered Feb 23 '26 03:02

Yamahari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!