×

C++ Classes and Objects


Introduction to Classes & Objects

What is class ? Why is it being used in Object-oriented programming languages? What is actually an Object oriented programming?

Do you play games? Yes, a game like super mario, Pacman, breakout game, snake game, etc. These different types of games are the part of one big blueprint named as "GAME" :). So there is something which creates a blueprint of various types of games and keeps them together in a player like video games device (eg, Play Station etc).

What is Class ?

As i explained in above example , Class is just a blueprint which contains stuff like properties , variables, member functions and all . A class defination starts with class keyword followed by classname and class body is enclosed by pair of paranthesis followed by semicolon .

Syntax :-

class ClassName
{
public or private or default or protected : 
   int a; 
   float b;
};

where,

ClassName :- is the name of class

public or private or default or protected : are the access modifiers. You will get the best tutorial on this later.

int a; float b; are called as data members of class.

Rules for naming convention of ClassNames

1) ClassName must start with uppercase letter.
2) C++ follows camelCasing pattern . First character  must starts with capital letter for each new word you write after the old word.  
For example :- BreakClass , GameClass , BirdClass, BankClass .

What are Objects :-

Objects can be anything . An object is just an instance of class which holds the data variables declared in class and the member functions work on these class objects.

Syntax for creating Objects in C++

Classname objectsInstanceName;

Example :-

1) Game snakeGame;
2) Game pacmanGame;
3) Game chessGame;

As you see , we created multiple instances of class Game. First instance or object is snakeGame . Second instance or object is pacmanGame. You can create multiple instances or objects of a class. You can assign state, behaviour, properties to these instances or objects.

Assigning state, behavior , properties to an objects

1) snakeGame.eat();
2) pacmanGame.walk();
2) chessgame.move();

An object can have state, behavior . That's why Objects are called as Physical and logical entities . Objects allocates memory .
whereas,
Class are only logical entities. They do not exist .They are just a blueprint . No memory is allcated for classes. 

Example :-

#include <iostream>
using namespace std;
class Game
{
public:
  int i;                   //data variable
  void  display(string str)         //Member Function
  { 
   cout<<str<<"\n";
  }
}; // Class ends here . Never forget this semicolon. 

int main()
{
 Game sankeObject;                     // Creatig Game class's object
 sankeObject.display("Sanke Game");    //Calling member function using class object

 Game pacmanObject;
 pacmanObject.display("Pacman Game");
}

Output :-

Snake Game
Pacman Game