C++ CLASSES & OBJECTS

A class is a mechanism for creating user-defined data types. It is similar to the C language structure data type. In C, a structure is composed of a set of data members. In C++, a class type is like a C structure, except that a class is composed of a set of data members and a set of operations that can be performed on the class.
In C++, a class type can be declared with the keywords union, struct, or class. A union object can hold any one of a set of named members. Structure and class objects hold a complete set of members.

Each class type represents a unique set of class members including data members, member functions, and other type names. The default access for members depends on the class key:

Class Syntax

class class_name
{

     private :
        Variable declaration;
        Function declaration;
    public:
        Variable declaration;
        Function declaration;
};

The Class declaration is similar to a struct declaration. The Keyword Class specifies, that what flows is an abstract data of type class_name. The body of a class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions are variables are collectively called class members. They are usually grouped under two sections, namely, private and public to denote which of the members are private and which of them are public. The keywords private and the public are known as visibility labels.

[quote]Note that these keywords are followed by a colon.[/quote]

The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also.

The data hiding(using private declaration) is the key feature of object-oriented programming. The use of the keyword private optional. By default, the members of a class are private. Such as class is completely hidden from the outside world and does not serve any purpose.

The variables declared inside the class are known as data members and the function are known as member functions. Only the member functions can have access to private data members and private functions. However, the public members (both functions and data) can be accessed from outside the class.

Example

class Item 
{ 
    int itemNo; 
    float itemCost; 
   public: 
     void getData(int x, float y); 
     void putDate(void); 
};

Creating objects

Once a class has been declared, we can create a variable of that type by using the class name.
[quote]Item x;[/quote]

Creates a variable x of a typed Item. In C++ the class variables are known as objects. ‘x’ is called an object of a type Item. We may also declare more than one object in one statement.
Item x,y,z;

The declare of an object is similar to that of a variable of any basic type. The necessary memory space is allocated to an object at this stage.

[quote]Note that class specification, like structure, provides only a template and doesn’t create any memory space for this on objects.[/quote]

How to Access Class Members

Class Members can be accessed after a class is defined and objects are created. The general syntax to access class member:
[quote]Object_name.function_name(arguments);[/quote]

The dot (‘.’) used above is called the dot operator or class member access operator. The dot operator is used to connect the object and the member function. This concept is similar to that of accessing structure members in the C programming language.

The private data of a class can be accessed only through the member function of that class. For example,
A class and object are defined below:

class Add 
{ 
    int a, b; 
   public: 
    void sum(int,int); 
}e1;

[quote]Then the member access is written as e1.sum(5,6);[/quote]

Where e1 is the object of class Add and sum() is the member function of the class. It is also possible to declare more than one object within a class:

class Add 
{ 
    private: 
        int a; 
    public: 
        void sum(int) 
        { 
            /* body of the methos */ 
        } 
}; 
int main() 
{ 
    Add e1,e2;
    
    return 0; 
}

In these two objects, e1 and e2 are declared of class Add.

This is an important difference to recognize and understand in an object-oriented C++ programming language.

class Add 
{ 
    int x;   //Here access specifier is private by default 
};

struct Add
{
    int x; //Here access specifier is public by default
};

It is not always the case that the member function declaration and definition takes place within the class itself. Sometimes, the declaration of member function alone can occur within the class. In a situation such as this, it is important to understand the identifying member function of a particular class.This is performed by using the operator :: this is called scope resolution operator.

class Myclass 
{ 
    private: 
        int a; 
    public: 
        void getvalues() // Only Member Function declaration is done 
}; 
void Myclass :: getvalues() // Here Member Function is defined 
{ 
    /* Function Body */ 
} 
int main() 
{ 
    Myclass e1,e2;
    
    return 0; 
}

So the usage of the scope resolution operator is as follows:

Defining Member Functions

The data members of a class must be declared within the body of the class, whereas the member functions of the class can be defined in any one of the following ways:

The syntax of a member function definition changes depending on whether it is defined inside or outside the class specification.

Members Functions Inside the Class Body

/* Member functions defined inside the body of the student class */
#include <iostream> 
#include <string.h>
using namespace std;
 
class student 
{ 
    private: 
        int rollNumber; 
        char studentName[20]; 
    public: 
        void setdata(int number, char *name) 
        { 
            rollNumber = number ; 
            strcpy(studentName,name); 
        } 
        void putdata() 
        { 
            cout<<"Roll No="<<rollNumber<<endl; 
            cout<<"Name ="<<studentName<<endl; 
        } 
}; 
int main() 
{ 
    student s1; 
    student s2; 
    s1.setdata(1,"Balu"); 
    s2.setdata(10,"Tutorila"); 
    cout<<"Student details....."<<endl;
    s1.outdata();
    s2.outdata();
    
    return 0; 
}

The syntax for specifying a member function declaration is similar to a normal function definition except that it is enclosed within the body of a class. All the member functions defined within the body of a class are treated as inline by default except those members having looping statements such as for, while, etc., and it also depends on compilers.

Members Functions Outside the Class Body

/* Member functions defined outside the body of the student class */
#include <iostream> 
#include <string.h> 
using namespace std;
class student 
{ 
    private: 
        int rollNumber; 
        char studentName[20]; 
    public: 
        void setdata(int number, char *name);
        void putdata();
}; 
void student::setdata(int number, char *name) 
{ 
    rollNumber = number ; 
    strcpy(studentName,name); 
} 
void student::putdata() 
{ 
    cout<<"Roll No="<<rollNumber<<endl; 
    cout<<"Name ="<<studentName<<endl; 
} 
int main() 
{ 
    student s1; 
    student s2; 
    s1.setdata(1,"Balu"); 
    s2.setdata(10,"Tutorila"); 
    cout<<"Student details....."<<endl;
    s1.outdata();
    s2.outdata();
    
    return 0; 
}

Member functions that are declared inside a class have to be defined separately outside the class. Their definitions are very much like normal functions.

They should have a function header and a function body.

The general form of a member function definition is:

[quote]return-type class-name :: function-name(argument declaration)
{ function body; }[/quote]

Nested Member Functions Call 

A Member function can be called by using its name inside another member function of the same class is called Nested Member functions.

Example:

/* Member functions defined inside the body of the student class */
#include <iostream> 
#include <string.h> 
using namespace std;
class set 
{ 
        int m,n; 
    public: 
    void input(void); 
    void display(void); 
    int larget(void); 
};
int set::largest(void) 
{ 
    if (m>=n) 
        return(m); 
    else 
        return(n); 
} 
void set::input(void) 
{ 
    cout<< "input values of m and n:"; cin>>m>>n; 
} 
void set::display(void) 
{ 
    cout<<"Largest Value = "<<largest(); // calling member function 
} 
int main() 
{ 
    set A; 
    A.input(); 
    A.display();
    
    return 0; 
}

Static Data Members

A data member of a class can be qualified as static. The properties of a static member variable are similar to that of a C static variable. A static member variable has certain special characteristics:

Static variables are normally used to maintain values common to the entire class.

[quote]Note: The type and scope of each “static” member variable must be defined outside the class definition.[/quote]

Example:

#include <iostream>
#include <string.h>
using namespace std;
class item { 
    private: 
        static int count; //count is static int number; 
    public: 
        void getdata() 
        { 
            count++; 
        } 
        void getcount() 
        { 
            cout<<"count:"; 
            cout<<count<<"\n"; 
        } 
};
int item:: count; //count defined 
int main() 
{ 
    item a,b,c; 
    a.getcount(); 
    b.getcount(); 
    c.getcount(); 
    a.getdata(); 
    b.getdata(); 
    c.getdata(); 
    cout<<"After reading data"<<"\n"; 
    a.getcount(); 
    b.getcount(); 
    c.getcount(); 
    
    return 0;
}

[quote]

Output:

After reading data                                                                                                                                           
count:3                                                                                                                                                      
count:3                                                                                                                                                      
count:3  

[/quote]

Passing Objects as Arguments

It is possible to have functions, which accept objects of a class as arguments, just as there are functions, which accept other variables as arguments. Like any other data type, an object can be passed as an argument to a function by the following ways:

In the case, of pass-by-value, a copy of the object is passed to the function and any modifications made to the object inside the function are not reflected in the object used to call the function. Whereas, in pass-by-reference, an address of the object I passed to the function and any changes made to the object inside the function is reflected in the actual object. The parameter passing by reference is more efficient since only the address o the object is passed and not a copy of the entire object.

Passing objects by value

/* 
    The program illustrates the use of objects as function arguments in pass-by-value mechanism. 
    It performs the addition of two complex numbers
*/ 
#include <iostream> 
#include <string.h>
using namespace std;

class complex 
{ 
    private: 
        float real; 
        float img; 
    public: 
        void read(); 
        void add(complex c1, complex c2); 
        void display(); 
}; 
void complex::read() 
{ 
    cout<<"Enter real part and imaginary part of a complex number:"<<endl; cin>>real;cin>>img; 
} 
void complex::add(complex c1, complex c2) 
{ 
    real= c1.real + c2.real; 
    img=c1.img+c2.img; 
} 
void complex::display() 
{ 
    cout<<real<<"+i"<<img<<endl; 
} 
int main() 
{ 
    complex A,B,C; 
    A.read(); 
    B.read(); 
    C.add(A,B); 
    cout<<"The first complex no is "<<endl; 
    A.display(); 
    cout<<"The second complex no is "<<endl; 
    B.display(); 
    cout<<"The addition of two complex nos is"<<endl; 
    C.display();
    
    return 0; 
}

[quote]

Output:
Enter real part and imaginary part of a complex number:
4
5
Enter real part and imaginary part of a complex number:
2
3

The first complex no is
4+i5
The second complex no is
2+i3
The addition of two complex nos is
6+i8

[/quote]

Passing Objects by Reference

/*
    - The program illustrates the use of objects as function arguments in pass-by-reference mechanism. 
    -  It performs the transform some amount form acc2 to acc1. 
*/
#include <iostream> 
#include <string.h>
using namespace std;
class AccClass { 
    private: 
        int accno; 
        float balance; 
    public: 
        void getdata() 
        { 
            cout<<"Enter the account number:"; 
            cin>>accno; 
            cout<<"Enter the balacne :"; 
            cin>>balance; 
        } 
        void display() 
        { 
            cout<<"Account number is:"<<accno<<endl; 
            cout<<"Balance is:"<<balance<<endl; 
        } 
        void MoneyTransfer(AccClass &acc,float amount) 
        { 
            balance=balance-amount; 
            acc.balance=acc.balance + amount; 
        } 
}; 
int main() 
{ 
    int trans_money; 
    AccClass acc1,acc2; 
    acc1.getdata(); 
    acc2.getdata(); 
    cout<<"Account Information...."<<endl; 
    acc1.display(); 
    acc2.display(); 
    cout<<"How much money is to be transferred from acc2 to acc1: "; 
    cin>>trans_money; 
    acc2.MoneyTransfer(acc1,trans_money); 
    cout<<"Updated Information about accounts....."<<endl; 
    acc1.display(); 
    acc2.display();
    
    return 0; 
}

[quote]Output is:
Enter the account number:100
Enter the balacne :5000
Enter the account number:200
Enter the balacne :7000
Account Information….
Account number is:100
Balance is:5000
Account number is:200
Balance is:7000
How much money is to be transferred from acc2 to acc1: 1000
Updated Information about accounts…..
Account number is:100
Balance is:6000
Account number is:200
Balance is:6000[/quote]

Returning Objects from functions

Similar to sending objects as parameters to functions, it is also possible to return objects from functions. The syntax used is similar to that of returning variables from functions. The return type of the function is declared as the return object type.

/* Addition of two complex numbers */ 
#include <iostream> 
#include <string.h> 
using namespace std;
class complex 
{ 
    private: 
        float real; 
        float img; 
    public: 
        void getdata(); 
        complex add(complex x); 
        void display(); 
}; 
void complex::getdata() { 
    cout<<"Enter real part and imaginary part of a complex number:"<<endl; 
    cin>>real>>img; 
} 
complex complex::add(complex x) 
{ 
    complex temp; 
    temp.real=real+x.real; 
    temp.img=x.img+x.img; 
    
    return(temp); 
} 
void complex::display() 
{ 
    cout<<real<<"+i"<<img<<endl; 
} 
int main() 
{ 
    complex A,B,C; 
    A.getdata(); 
    B.getdata(); 
    C=A.add(B); 
    cout<<"The first complex no is "<<endl; 
    A.display(); 
    cout<<"The second complex no is "<<endl; 
    B.display(); 
    cout<<"The addition of two complex no is"<<endl; 
    C.display(); 
    
    return 0; 
}

[quote]Output:
Enter real part and imaginary part of a complex number:
3
4
Enter real part and imaginary part of a complex number:
5
6
The first complex no is
3+i4
The second complex no is
5+i6
The addition of two complex no is
8+i12[/quote]

Points to remember

Classes have all of the properties that we described for structures plus all the properties associated with member functions. The following is a list of some points to keep in mind when using classes.