Classes and Objects in C++: Differences Explained

  • Context: C/C++ 
  • Thread starter Thread starter torquerotates
  • Start date Start date
  • Tags Tags
    Classes
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 2K views
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?
 
Physics 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.