C/C++ Classes and Objects in C++: Differences Explained

  • Thread starter Thread starter torquerotates
  • Start date Start date
  • Tags Tags
    Classes
AI Thread Summary
In C++, the distinction between a class and an object is fundamental to understanding object-oriented programming. A class serves as a blueprint or template that defines the properties and behaviors of a type of object. It is defined once within a program and can be used to create multiple instances, known as objects. An object is an instantiation of a class, representing a specific instance with its own unique data. For example, in the provided code snippet, the class "Cars" defines the structure for car objects, while "Lamborghini" and "Civic" are specific instances created from this class. This relationship can be likened to a cookie cutter (class) that shapes cookies (objects). The class encapsulates the definition, while the object embodies the actual entity. Understanding this difference is crucial for effective programming in C++.
torquerotates
Messages
207
Reaction score
0
In C++ what is the difference between an object and a class? I'm confused, is an object always a class?
 
Technology news on Phys.org
An object is what is instantiated from a class.
A class is defined once in a program. From this class, an object can be created (instantiated) from the class, according to the parameters specified. The object so created is an instance of the class. Hence it is possible to instantiate multiple object from the same class.

Here's an example:
// following is the class definition
class Cars
{
char *name;
public:
double price;
Cars(char *n, double p){name=n;price=p;}
};
int main(int argc, char *argv[])
{
// following are pointers to objects, or instances of the class Cars
Cars *Lambourghini=new Cars("Lambourghini", 300000.0);
Cars *Civic=new Cars("Civic", 35000.0);
return 0;
}
 
An object is a specific thing. A class is a kind (or type or category) of thing.

Another way of looking at it is to say that a class is a template or "cookie cutter" for creating things (objects) that have the same set of properties.
 
It's the same as if you say "int i". "int" is the type and i is a variable of that type.

If I define a class "myClass" and then say "myClass x", "myClass" is the class and "x", a variable of that type, is the object.
 
Object is every person like "you" "me" and "HallsofIvy"...
Class is a definition say: Physicsforumer
 
If you are familiar with PHP, this tutorial explains how objects are instantiated from a class; it gives a good feel about what role objects play. The tutorial is light-hearted.

http://devzone.zend.com/node/view/id/638
 
Last edited by a moderator:
A class is a cookie cutter. An object is a cookie.
 

Similar threads

Replies
35
Views
4K
Replies
8
Views
2K
Replies
23
Views
2K
Replies
36
Views
3K
Replies
34
Views
4K
Replies
4
Views
1K
Replies
4
Views
2K
Back
Top