Wednesday, January 2, 2013

Class and Objects in OOP Language

This post is specifically for a newbie for an object oriented programming(OOP), this is about what is a class and object in an OOP Language along with an example,

A class is a definition of an object.Its a combination of data representation(variables) and method declaration.The data and methods within a class are called members of class.
A Class is a type just like a int.

Object is an instance of a class. or we can say an object is just a variable of a class.

say for ex:
1)  int a; // here "int" is a type, "a" is a variable of type int 
so w.r.t above example int specifies a class and 'a' specifies a Object of a class int.

2) A real world example for class and objects 
Consider species birds, under birds species n number of animals will comes all those are objects of class birds.
say, Birds - Class
sparrow,ostrich,parrots,penguins etc etc are objects of class Birds 

Now we can come to a conclusion that an object is a real world entity which has its own characteristics,and originated from a type of class.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.

class Birds
float age;
float weight;  

int main()
Birds *parrot;  //parrot of Class Birds
Birds *penguin;  //penguin of Class Birds

parrot.age = 3;
parrot.weight = 5;
penguin.age = 8;
penguin.weight = 12;

cout << "parrot is an object of class Birds, and its age is"<<parrot.age<<"years old and weight is"<<parrot.weight <<"kgs";
cout << "penguin is an object of class Birds, and its age is"<<penguin.age<<"years old and weight is"<<penguin.weight <<"Kgs";

return 0;

The output of the above example program is as below:
parrot is an object of class Birds, and its age is 3 years old and weight is 5 kgs.
penguin is an object of class Birds, and its age is 8 years old and weight is 12 kgs.

the properties of an object can be accessed by the help of dot(.) operator as shown in above example like parrot.age

Hope you guys enjoyed the post,any comments or suggestions is acceptable.

No comments:

Post a Comment