|

What is a Class and Object in C++?

Question Description: What is a Class and Object in C++?

Can we say that a Class is an Object?

Expert Answer

A Class is like a blueprint, an object is like a house built from that blueprint.

You can have many houses with the same layout/floorplan (read class), but each is its own instance (read object). Each has its own owner, furniture, etc.

Note that there are also objects whose blueprint is not a class (e.g. integers).

I will try to give a more technical explanation rather than an abstract one. I think that definitions like “a class is a blueprint and an object is something made from this blueprint” are impossible to understand for newbies simply because these kinds of definitions are abstract and context-less.

Classes and objects have a pure abstract meaning in the object-oriented world but for simplicity, I will reduce the definition to a more practical one.

Consider the following statement:

int a;

“int” is a type and is “a” is a variable that has the type “int”.

C++ provides various ways to let the programmer define new types; for example:

typedef int* int_ptr;
int_ptr a;

In this example, a new type is defined int_ptr. “int_ptr” is a type, “a” is a variable that has the type “int_ptr”. Another example:

struct Point
{   
    int x;
    int y;
};
Point a;

Here, a new type is defined, “Point”, and “a” is a variable that has the type “Point”.

So what is a class in C++? A class is another way to define a new type, just like the other ways mentioned above.

What is an object? An object is a variable that has a type that was defined using the class keyword.

For example:

class SmartPoint
{
public:
   Point(x,y);
   Move(x,y);
protected:
   int x,y ;
};

SmartPoint a;

In this example, a new type is defined, “SmartPoint”, and “a” is a variable that has the type “SmartPoint”.

You may ask then what is different between a type defined by using the “class” keyword or “struct” keyword or “typedef” — but that is a matter for another discussion.

Similar Posts