Skip to main content

Introduction to Classes in C++

Classes are the building blocks of Object Oriented Programming in C++ language. Class gives us the ability to simplify certain types of programs by creating objects that forms the basis of Object Oriented programming.

Just like identifiers of built-in data types (ex. int, char etc.) are known as variables similarly identifiers (instances) of class are known as Objects.

Classes in C++ have two parts, data and functions; these are known as data members and member function respectively. Member functions are usually the means of accessing and modifying data members.

Anything inside the class can be either private to the class or public to the program. Classes may have both type of members (private and public) at the same time.

General form of Class:

  class class_name
  {
   access-specifier:
   member…
   member…
   member…

   access-specifier:
   member…
   member…
   member…
  }object-list;

Few points to remember:

  • Access-specifier can be anyone of the three private, public and protected.

  • Anything after an access-specifier has that type of access until another access-specifier is encountered.

  • There can be any number of access-specifier, but in general all the members having same access are grouped together under one access-specifier.

  • So,

    
    class c1
    {
     private;
       int a;
       int b;
          
     public:
       int c;
         
     private:
       int d;
    };

    Should be written as

    class c1
    {
     private:
       int a;
       int b;
       int d;
          
     public:
       int c;
    };
         
  • Object list is optional which is used to declare objects of the class.

private and public Access-Specifiers

private tells the compiler that the members following it are private to the class and can not be accessed by other parts of the program.

Ex.


  class c1
  {
   private:
     int a;
     int b;
     void func();
  };

Here, the variable a, b and function func() can can only be accessed by the members of the class c1.

On the other hand, public members are accessible to the other parts of the program also.


  class c1
  {
   private:
     int a;
     int b;
     void func();
   public:
     void func2();
     int c;
  }obj;

Here the variable c and function func2() are accessible from other parts of the program, but the private members are only accessible from the public function func2().

The public members of the class (i.e. func2() and c) can be accessed from other parts of the program with the help of the following syntax:

obj.c=10;

functions (public) are also accessed like this:

obj.func2();

A few points to remember:

  • Please note that in the previous example a, b and func() can not be accessed from other parts of the program with the help of (.) operator.

  • Member functions can simply access any of the private and public members of the class without the use of (.) operator.

  • For example, if func2() is a member function class c2 then it can access other members (both private and public) as shown below:

    func2()
    {
     a=b;
     b=c;
     func();
    }
    

Enough talking… Now let us move on to a simple program to illustrate:

  • How to define a class and its objects in C++.

  • Use of private and public access-specifiers.

  • How to define and use member functions.

  //C++ Program
  #include<stdio.h>
  #include<iostream.h>

  class employee
  {
   private:
   char name[30];
   int emp_no,age;
   float salary, net_salary, tax;
   void calculate()//in line function
   //used for the short ones
   {
   net_salary=salary-tax;
   }

   public:
   void input();
   void output();
  };

  //----FUNCTION DEFINITION STARTS----
  void employee::input()
  {
   printf("Enter Name: ");
   gets(name);
   printf("Enter Employee Number: ");
   cin>>emp_no;
   printf("Enter Age: ");
   cin>>age;
   printf("Enter Salary: ");
   cin>>salary;
   printf("Enter Tax Paid: ");
   cin>>tax;

   //the function below can only be invoked
   //from the member function like here
   //and not from the other parts of the program
   calculate();
  }

  void employee::output()
  {
   printf("\n\n EMPLOYEE DETAILS\n");
   //'\n' is used to print to the next line
   printf("Name: %s\n", name);
   printf("Age: %d\n", age);
   printf("Employee Number: %d\n", emp_no);
   printf("Net Salary: %f\n", net_salary);
  }
  //----FUNCTION DEFINTION ENDS----

  void main()
  {
   employee e1;

   e1.input();
   e1.output();
  }

A few points about the program:

  • Notice how member functions are used to modify data members of the class.

  • Notice the use of private function calculate(), that can only be accessed from other member function (i.e. input() and output()).

  • Notice how the member functions are declared and defined.

This article has gone a bit too long but once the discussion on topics like classes in C++ starts it never seems to end -;)

Good-bye for now!

Popular posts from this blog

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {      // } //*/ //* Toggle line if ( 2 ) {      // } else {      // } //*/ Now see how easy it is to toggle a part of PHP code by just removing or adding a single " / " from th

Introduction to Operator Overloading in C++

a1 = a2 + a3; The above operation is valid, as you know if a1, a2 and a3 are instances of in-built Data Types . But what if those are, say objects of a Class ; is the operation valid? Yes, it is, if you overload the ‘+’ Operator in the class, to which a1, a2 and a3 belong. Operator overloading is used to give special meaning to the commonly used operators (such as +, -, * etc.) with respect to a class. By overloading operators, we can control or define how an operator should operate on data with respect to a class. Operators are overloaded in C++ by creating operator functions either as a member or a s a Friend Function of a class. Since creating member operator functions are easier, we’ll be using that method in this article. As I said operator functions are declared using the following general form: ret-type operator#(arg-list); and then defining it as a normal member function. Here, ret-type is commonly the name of the class itself as the ope