C++ Objects and Classes

Classes are used to create your own custom reusable data types which are called objects.  A class is a blueprint that defines the variables (data) and the methods (functions) common to all objects(members) of a certain kind. For example, let us consider a class called fruits. This class can have different objects called apple,mango,banana etc. They are instances of the class fruits. Variables common to this class can be colour of the fruit,shape of the fruit,price of the fruit etc. Methods common to this class can be printing out the name of the fruit to the user. Methods are like behaviours of the object. These class members are shared by all objects in the class.

For declaring a class ‘fruits’:

class Fruits
{
public:
    int priceperkg;
    string color_of_fruit;
};

Here we have declared a class called Fruits with 2 member variables priceperkg and color_of_fruit that are public that will contain the price per kg and the colour of the fruit respectively. Public is the access modifier.The class definition ends with a semi-colon.

Now that we have created a blueprint for instances by creating the class, let us create objects. The objects or instances that we create of the Fruits class will be called as Fruits object and will have unique names.

void main()
{
     Fruits Apple;
     Fruits Orange;     

     Apple.priceperkg = 150;
     Apple.color_of_fruit = “red”;

     Orange.priceperkg = 100;
     Orange.color_of_fruit = “orange”;
 }

We are using the dot operator to assign values to the objects. We have created 2 objects or 2 instances of class Fruits called as Apple and Orange. The price of apples per kilogram is 150 and the colour of an apple is red. The price of oranges per kg is 100 and the colour of an orange is orange.

To initialise the members of the objects of a particular class, with some value , you can use the brace syntax.

Fruits Apple{150,”red”};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: