Taner Şenyurt

Kişisel gelişim sitesi…

Difference between C++ Class and C struct


C struct and C++ class structure is similar but by the default they have a difference in data hiding.
In struct doesn’t provide data hiding by default but class provides data hiding by default.
And the other difference is, class provides us to polymorphism and inheritance features.
We said class structure data hiding is coming default but what it means?
It means when we have a struct it is public by default so we can access our struct model wherever are we

  1. struct car{
  2. static int *model;
  3. int *horsePower;
  4. string *producer;
  5. }
  6. car myCar;

By myCar i can access my model,horsePower or producer because it works like public variable but same structure with class

  1. class car{
  2. static int *model;
  3. int *horsePower;
  4. string *producer;
  5. };
  6. car myCar;
  7. car myCarToo;

But in class structure i don’t have a direct access to my model,horsePower or producer if i want to access these variables i have to write a function which is accessing to them.So that i can only access these variables from functions.
That’s why class structure has a accessing levels like public ,private and protected.Generally variables written as public but it’s not a rule.And functions written as public to access these variables, think that way there is a horsePower variable and we have two functions named as setHorsePower and getHorsePower.In other class we can’t access horsePower variable because it’s private so that we have to access public functions to affect that variable.

In other case when we create a instance of object(car) we just won’t work in class , we simply create a copy of class and work on it.It means if we create two instance of car and we changed horse power of myCar it doesn’t affect the other instances of car(myCarToo).Every instance works on their copy.But sometimes we don’t want this ,when we don’t want this we have to describe our variable as static variable like “static int *model”.

Sorry about my English and if i tell something wrong please tell me :)

posted under C & C++, Programming

Comments are closed.