Classes and objects in CPP

In this c++ tutorial, we will learn the basics of classes and objects in CPP. Also, we have provided an easy example.

Classes and objects in c++

Consider an example of a company, where there are manager, assistant manager and employees. Now, the manager wants that some data can only be accessed by him, not by other members of the company. And he wants that some information should only be shared with the assistant manager, not by employees. The assistant manager wants some data of his can only be accessed by him and not by employees. So, in this kind of situations, we use access modifiers in a class in object-oriented programming.

What is Class in C++?

A class is a user-defined data type which has data members and member functions of its owns that can be accessed by creating an instance of that class. We can say, Classes, are the building blocks of object-oriented programming.

Declaration of class: A class is defined using keyword class followed by user-choice class name then using data members and member functions inside curly brackets ending with a terminator ( ;).

  class Codespeedy            // codespeedy is the class name

   private :                 // by default data members are private

     int salary ;
     int tax ;

    public :                

    void get();
    void print ();

Note:- When a class is declared no memory is allocated to the class, memory is allocated when an instance of that class ( object ) is created.

How to Access data members and member functions of a class in CPP?

Data members and member functions of a class can be accessed by creating an object of class and access using dot ( . ) operator.

Syntax:-    Codespeedy C; // Codespeedy is the class name and C is the object for a class



The control of accessing data members and members functions can be define using Access Modifiers which are of three types:-

private in C++

private data members and member functions are limited to a class only, they can not be inherited by any other class. By default, data members are member functions are private.

protected in C++

data members and member functions defined private cannot be accessed by outside class similar to private but they can be inherited by a derived class.

public in C++

public data members and member functions are accessible anywhere using dot ( . ) operator.

Class implementation in c++ accessing data members outside the class definition


 using namespace std;

  class Codespeedy
   int data ;
    public :
     void get_data ();
     void show_data ();

   void Codespeedy :: get_data()
      int x;
    cout<<" Enter value of data is :"<<endl;
      data = x;

  void Codespeedy :: show_data()
    cout<<"Value of data is :"<<data<<endl;

 int main()
    Codespeedy C;

Also learn,

Leave a Reply

Your email address will not be published. Required fields are marked *