info@tutsfinder.in



Class and Objects


Class


Class is a type that defines the implementation of a particular kind of object.

A class is a blue print of the object. A class describes all the attributes and methods of object.

Class keyword is used to declare the new class.

• Data(variables) and methods defined within the class.

• Variables and methods are called members of class.

• Data are data members or instance variables of the class.

• Methods are called member functions of the class.

Example – A class that models a car looks like the following


class Car
{
	//attributes
	String brand;
	String color;
	String model;

	//methods
	void gearChange();
	void gateOpen();

}


Object


An object is an instance of class. An object is an real world entity that has some attributes, behavior and identity. Attributes and behavior of an object are defined by the class definition.

A class is like a blueprint , and declaring a class alone has no effect on the execution of a program.

Objects have states and behaviours -

• State defines the characteristic of the object e.g. Car brand is BMW, color Black etc.

• Behaviour defines the functionality of the object e.g. gear change, sun roof open etc.


Example: In this example we have created a Car class which has one method printInfo() . We have creating a object of Car class and print it.

#include <iostream>
using namespace std; 
class Car 
{ 
    // Access specifier 
    public: 
  
    // Data Members 
    string brand;
    string model;
    string color;
  
    // Member Functions() 
    void printInfo() 
    { 
       cout << "Details about Car : " << brand+" "+model+" "+color << endl; 
    } 
}; 
  
int main() { 
  
    // Declare an object of class geeks 
    Car obj; 
  
    // accessing data member 
    obj.brand = "BMW";
    obj.model = "X5";
    obj.color = "Black";
  
    // accessing member function 
    obj.printInfo(); 
    return 0; 
}


Output:

Details about Car : BMW X5 Black