Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access members of derived class through base class pointer C++

Is there any way to have a general code access members of derived class through base class pointer? Or any other way around this?

Let's say I have a class Shape. I have classes Square and Triangle which inherit it. Both have their own private members which have nothing to do with each other so there is no point in having them in the base class. Now, what if I need to write a class into a file, but I don't know if the class is Square or Triangle until the moment I need to write it in the file?

I've been trying to figure out how to solve this problem. The worst case solution would be to write the data of both Square AND Triangle into a file, add an identifier (Triangle or Square) for both reading and writing and have a small parser put the class together when loading data. This would be inefficient and waste of time.

I was wondering if there is some trick or design pattern or anything that can help with the situation.

like image 932
user1646394 Avatar asked Dec 16 '22 19:12

user1646394


2 Answers

This serialization should be done using virtual functions. Define a function in the base class that shall serialize the object. The Triangle and the Square overrides this functions and write

  • the identifier
  • all data that should be serialized

You may implement the common part in the base class if appropriate.

When you want load the file you will need factory method that creates the class instance corresponding to the identifier. The new instance virtual deserialize method must be called to load the actual data.

like image 164
harper Avatar answered Jan 28 '23 11:01

harper


You can have a pure virtual getter in your Base Class. and all your Derived classes will override that. like this

class Shape{
  public:
    virtual int data() const = 0;
};
class Square: public Shape{
  private:
     int _member;
  public:
    virtual int data() const{
     //do something with private members and return it
     return _member;
    };
};
like image 41
Neel Basu Avatar answered Jan 28 '23 09:01

Neel Basu