What is a Class and Object in C++?

前端 未结 20 952
走了就别回头了
走了就别回头了 2020-12-09 10:33

What is a Class and Object in C++?

Can we say that a Class is an Object?

20条回答
  •  北海茫月
    2020-12-09 11:12

    I will try to give 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 kind 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 which 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 which 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 which 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 which 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 which 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.

提交回复
热议问题