C++ Inheritance

While using OOP (Object Oriented Programming) we have to operate on classes, so we create our own class, for example class CFurniture:

class CFurniture

   Cfurniture(); // constructor
   ~Cfurniture(); // destructor

   int GetType() { return itsType; } // method/accessor
   void SetType(type) { itsType = type; } // method/accessor

protected: //if we want to inherit this variable in another class, we have to use protected type (private is not visible outside this class)
   int itsType;


And then we create another class, which is strictly connected with CFurniture, e.g. CTable:

class CTable : public Furniture
  CTable(); // constructor
  ~CTable(); // destructor
  char GetColor() { return itsColor; } // method/accessor
  void SetColor(char color) { itsColor = color; } // method/accessor

  char itsColor;

In main() we are going to call the SetType() (to set) and GetType() (to get type) methods:

int main()
CTable Table;
Table.SetType(6); // here we set type of our table - type 6
cout << "This table is " << Table.GetType() << " type!" << endl; // here we get our set type
return 0;

You can see that it is very simple and we don’t have to create another methods in another class to activate it in main().



Zostaw komentarz

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s