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

{
public:
   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
{
public:
  CTable(); // constructor
  ~CTable(); // destructor
  char GetColor() { return itsColor; } // method/accessor
  void SetColor(char color) { itsColor = color; } // method/accessor

private:
  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().

 

MJ

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

w

Connecting to %s