Skip to main content

Classes and Objects

C++ is an object oriented language. An object oriented language works on the principle of objects - which contain within themselves data and functions which modify this data.

Objects are created with the help of classes. Let us what are these classes first.

Classes

A class is a code template from which objects are created. A class defines what data members an object must have and what functions it must have. 

An object has a state and behavior similar to real life object. State is data of the object. Behavior is what it can do. e.g. if we consider a pencil - it has state - what is color, length, diameter etc. It has behavior - it can write. 

A class defines what are these state and behavior. 

In programming paradigm class is similar to data type and object is a variable of this type. Or object is one instance of this class.

Defining a class 

A class is defined using the keyword class followed by its name and followed by class members within braces.

class dog
{
   int age;
   int color;
   char name[20];
public:
    void bark(){}
    void eat(){}
    void run(){}
};
Here dog is a class.

It has the data members age, color and name - each of which is defined using a data type. It also has functions or methods - bark(), eat() and run()

This class definition is a statement and like any other statement in C++, it must be terminated with a semicolon;

Creating objects

Let us see how to define few objects of this class.

#include<iostream>
using namespace std;
class dog
{
   int age;
   int color;
   char name[20];
public:
    void bark()
    {
      cout<<"Woof, woof"<<endl;
    }
    void eat(){
      cout<<"it eats"<<endl;
    }
    void run() {
      cout<<"it runs"<<endl;
    }
};
int main()
{
   dog tommy;
   tommy.bark();
   tommy.eat();
   tommy.run();
   //tommy.age = 3;
}

Here we created an object of class dog with name tommy. Then we call three methods on this objects with the help of dot operator. We rewrote the previous definition of the class by adding implementations of all 3 methods.

The output of the program is
$ ./a.out
Woof, woof
it eats
it runs

Dot operator


Dot operator is used to access members of an object. In the above example, tommy.bark() is used to call bark() function with tommy object.

Access specifiers - public, private and protected


The commented line tommy.age=3, is wrong. If we uncomment it the program throws an error. Why?

Each member of a class has an access specifier associated with it - which tells who can access it. It specifies which members are part of the interface of the class and so is accessible to users of the class and which members are for internal use of the class.

Three access specifiers are public, private and protected. 

public members of a class are accessible from the users of the class. They are visible everywhere. Most of the functions of a class are made public.

private members of a class are internal to the class. They can be accessed only from the functions of the class. They are hidden from the users of the class. The advantage of this data hiding is that you can change the implementation of a class without affecting the users. Default access specifier for a class is private.

protected members of a class are visible to the member functions and its subclasses. 

In the previous class definition  age, color and name are all private members of dog class. But the methods bark(), eat() and run() are public as they are preceded by public specifier.

There can be multiple access blocks in a class. Once an access specifier is mentioned all members belong to that access mode, until there is next access specifier.

e.g.

class book
{
    int num;
    char name[30];
public:
    char author[40];
    float price;
protected:
    int year;
public:
   void lend_book();
   void return_book(); 
};
Here
  • num and name are private as they don't have access specifier
  • author and price are public - they are written after public keyword
  • year is a protected member as it is preceded by protected keyword
  • lend_book() and return_book() are both public
The common practice in C++ is to
make data members of a class as private and methods of a class as public.

This will help users to know the interface of the class without worrying about implementation. 
If data members are private, how can user access them? 
Data members of a class are initialized with the help of special methods called constructors and they are accessed using constant methods called getters. 

Difference between class and structure 

C++ also has struct keyword similar to C. But unlike structures in C, C++ structures can have function members also. 

If that is the case, what is the difference between a class and a structure in C++?

The difference is struct members are public by default and class members are private by default.

But you can still use access specifiers in struct s also to change this.

Let us look at an example.

#include<iostream>
using namespace std;
struct circle
{
   float radius;
   int x,int y;
   void display_area()
   {
      float area = 22.0/7 * radius*radius;
      cout<<area<<endl;
   }
};
int main()
{
    circle c1;
    c1.radius = 7;
    c1.display_area();
}
Here we are changing radius of c1 object outside of structure without getting any errors. Because radius and all other members of the class are public here in the structure.

We conclude this discussion with one last fact. The implementations of methods are often defined outside of class body using scope resolution operator in .cpp file where as class body with member declarations are written in .h file.  We will see that in depth in the next post.

Pointers to Objects


You can define  pointers to objects and assign them to addresses of existing objects. Or you can create an  object  dynamically, using   new operator.

class A{/***code***/};
int main()
{
 A *ptr1;/*pointer to object*/
 A obj1;
 ptr1 = &obj1;
 A *ptr2 = new A;
 delete ptr2;
}

In the line A *ptr2 = new A; an object is created, its constructor is called and address of object is stored in pointer ptr2.

Such dynamically created objects must be explicitly released using delete operator. delete operator releases memory and calls destructor for the object. delete operator is similar to free() function in C.

     delete ptr2;

As in the case of structures in C, members of objects pointed by a pointer are accessed using arrow operator (->).

#include"circle.h"
#include<iostream>
using std::cout;
int main()
{
 Circle *cptr = new Circle;
 cptr->set_center(0,0);
 cptr->set_radius(7);
 cptr->print_area();
 delete cptr;
}
 


 

Comments

Popular posts from this blog

Find the error in C++ program

This C++ program is not compiling. What do you think is the error with the program? #include<iostream> using namespace std; int main() {    int arr[10];    arr={1,2,3,4,5,6,7,8};    cout<<"arr[0]="<<arr[0];    return 0; } Is the error due to Not using printf Initialising the array with only 8 elements instead of 10 Initialising array in the next statement instead of in definition. None of the above  Now if you like this question, there are plenty more questions like this and programs and notes in my app Simplified C++. Download the Simplif ied C++   by Hegdeapps now By the way the correct answer is (3)

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t...

Friends of C++

Friend function Remember that a member which is not public (Private and protected )  can not be accessed from outside the class.  Three are some situations where you may need to access these. Keyword friend  is used for this. A friend functions and classes can access all members of a class.  This concept is controversial. People say friend concept violates data encapsulation  A friend function is a non-member function but still can access all the members of a class including private members. Such a function is declared within class body with the prefix "friend" class Number { int num; public: Number( int m){ /*code*/ } friend void printNum(Number ob); /*friend function*/ }; void printNum (Number obj) { cout << obj.num << "endl" ; } printNum() is not member of class Number . But it can still access all members including private members, because it is a friend. Friend class An object of a friend c...