Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Classes and objects

  1. Oct 26, 2008 #1
    In C++ what is the difference between an object and a class? I'm confused, is an object always a class?
     
  2. jcsd
  3. Oct 26, 2008 #2
    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;
    }
     
  4. Oct 26, 2008 #3

    jtbell

    User Avatar

    Staff: Mentor

    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.
     
  5. Oct 27, 2008 #4

    HallsofIvy

    User Avatar
    Staff Emeritus
    Science Advisor

    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.
     
  6. Oct 27, 2008 #5

    zyh

    User Avatar

    Object is every person like "you" "me" and "HallsofIvy".....
    Class is a definition say: Physicsforumer
     
  7. Nov 4, 2008 #6
  8. Nov 4, 2008 #7
    A class is a cookie cutter. An object is a cookie.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Classes and objects
Loading...