C++ Classes and Objects

C++Classes and Objects


C++ Classes and Objects
In computer programming, C++ is an object-oriented programming language. Therefore C++ is totally based on classes and objects, along with its attributes and methods. For example: in real life, there are various types of vehicles like cars, bicycles, trucks, autos, and so on. Therefore vehicles are classes and their types are objects.
Class: 
  • Class is the template (Format).
  • The C++ class mechanism allows users to define their data types. For this reason, Class is called user-defined data-types.
  • Class is created by class keyword.
The class definition has two parts:
  • Class head- compose of keyword class followed by class name.
  • Class body- enclose by pair of curly braces is as follows: {…….}
The Syntax of the class is as follows: 
class class_name
{
private:
// declaration of variables
// declaration of functions
protected:
// declaration of variables
// declaration of functions
public:
// declaration of variables
// declaration of functions
};
Object:  
  • An Object is a Physical existence.
  • An Object is an instance of a class.
  • An object is a combination of or collection of data and code designed to emulate a physical or abstract entity. 
Objects serve the following purposes:
  • Understanding the real world and a practical base for designers.
  • Decomposition of problems into objects depends on judgment and the nature of the problem.
  • Every object has attributes and behavior called operations.
  • The attributes are the data structures representing the properties of the objects.
The Syntax of object is as follows: 
class_name object_1, object_2, object_3 …… object_n;
Example: Create class and objects then find area of room is as follows
Output
C++ Class Methods
In this tutorial, you can have learned about C++ Class methods that are also called functions.
There is two ways declaration of Methods for our class is as follows:
1.Defining Member Functions Inside the Class Declaration
  • Member functions defined inside the class declaration are called inline functions
  • Only very short functions, like the one below, should be inline functions
        int getSide()
        { return side; } 
Example
Output
 
2.Defining Member Functions After the Class Declaration *preferred way
  • Put a function prototype in the class declaration
  • In the function definition, precede the function name with the class name and scope resolution operator (::)
int Square::getSide()
{
return side;
}
Example
Output