Menu

Class in C++

  • Class is a collection of related data members and member functions combine into a single unit.
  • A class is declared with the keyword 'class'.
  • A class is a user-defined data type.
  • The variables enclosed in class are called data members and the function enclosed in class are called member functions.

Syntax

        class class-name{
            access labels:
            data member1;
            data member2;
            .............
            data membern;
            member function1;
            member function2;
            .............
            member function n;
        };

Example

        class sum{
            int num1;
            int num2;
            int sum;
            private:
            void inputdata();
            void processdata();
            void outputdata();
        };

Description

  • In the above example, the sum is the class name with the data members and the member functions respectively.
  • The data members here arenum1 with the datatype int, num2 with the data type int and sum with the data type int.
  • The access label here declared is private.The member functions here are inputdata(), processdata() and outputdata() with the datatype void.
  • The member function inputdata() for inputting the data variables, the member function processdata() for processing the data, and output data for producing the result.

Access labels(Access specifiers)

  • Access labels define the accessibility of data members to outside class or not.
  • There are 3 types of access labels,
    1. private
    2. public
    3. protected

private

  • private access labels cannot access the outside class.

public

  • It can access not only to the class but also to the outside of the class.

protected

  • A protected member variable or function is very similar to a private member but it is different in the case of inheritance provided one additional benefit that they can be accessed in child classes(derived classes).