jeudi 10 septembre 2020

How to access derived class properties from base class instance

I have the following code which I can't access or change:

class A{
}

class B:A{
    string name;
    int age;
    string desc;
}

class C:A{
    string name;
    int age;
    string desc;
}

I need to find a way to write a function that assigns values to instances of B and C. the naive way would be to write two functions. one for each class.

void myFunc(B b){
    b.name = "some_name";
    b.age = 27;
    b.desc = "some_desc";
}

void myFunc(C c){
    c.name = "some_name";
    c.age = 27;
    c.desc = "some_desc";
}

Is there a way to write one generic function that those the job? of-course those classes are only examples. In the real world there are many classes deriving from the base class and each class has many members.

Aucun commentaire:

Enregistrer un commentaire