Pages

Sunday, 9 September 2012

Learn C++

Module 9 :Static Polymorphism

Introduction

Static polymorphic behavior is realized at compile time. A class template acts as a generic class definition from which new class types can be defined by a simple change of parameter types. Whereas a normal class is used to create objects, a class template is used to define new class types, from which objects are then created. The compiler uses the types you supply, combined with the class template, to create a wholly new class type.
Understanding how to declare, implements, and use class and function templates will pay big dividends in many ways. Primarily, it provides you with a mechanism to write generic code. Learning to write generic code can potentially save you a lot of work.

Learning Objective


By the end of this Module, you will be able to:
  • Explain how to achieve static polymorphic behavior through templates
  • Explain how to write generic code using templates
  • Explain how to declare and implement function templates
  • Explain how to declare and implement class templates
  • Explain how to declare and implement class member function templates

Definition of Template

A template defines a related set of classes or functions. The related set of classes or functions defined by a template share the same code structure and functionality. The class or function template can then be used to declare a new class or function type.

Function Templates

A function template is a generic function declaration and definition from which different versions of the function can be created by the compiler based on the argument types used to call the function. If you think this sound a lot like overloaded functions you are right. Function templates and overloaded functions are related as you will soon see.

Class Templates

A class template is a generic class declaration and definition from which different, but related, class types can be created by the compiler based on type parameters.

Structure Templates

A structure template is like a class template but using structures instead.

How Templates Work: An Analogy

When you declare and define a template you are creating a generic version of whatever piece of code you are writing, be it a function or a class. In the declaration and definition of the template you will use one or more identifiers as type placeholders. These type placeholders are similar in function to the placeholders in a form letter generated with a word processor.
The below figure illustrates a simple mail merge operation. A master letter is created with placeholders for certain data elements. The structure of the data source is mapped to the master letter by the placeholder identifiers name and age. When the mail merge function is executed, the data source is merged with the master letter to yield the finished letters. The master letter is a generic document that can be reused to generate many specific letter instances. Class and function templates work in similar fashion. A generic function or class is declared and defined. Placeholders are inserted into the code to reserve spots for actual data types. When specific versions of a template function are required the type substitutions are made based on the types of the arguments used to call the function. In the case of template classes, a special syntax is used when a new template class is declared.

See: https://docs.google.com/open?id=0B_cy2j6cIeqTZ1VSbzJidkdkYlU

Declaring and Using Function Templates

Up until now, if you wanted to create different versions of the same function to operate on different data types you would overload the function. For instance, if you wanted to declare a function named Sum() that took two arguments, added them together, and returned the result you could create several versions of the function like so:
int Sum(int val1, int val2); 
float Sum(float val1, float val2); 
char Sum(char val1, char val2);
</pree>
These three functions can be replaced with one function template. 
<pre>
ifndef SUM_TEMPLATE_H 
define SUM_TEMPLATE_H 
template<class T> T Sum(T val1, T val2){ 
return val1 + val2;
} 
endif 
The Sum() function is declared to be a template by the keyword template appearing on line 4. Following the keyword template in angle brackets is the keyword class followed by a placeholder identifier named T. The class keyword as it is used here essentially means “any type”. The placeholder T will then appear somewhere in the function. It can appear in more than one place, as it does here in the parameter list. You can use any valid identifier as a placeholder name, not just T. You can also declare more than one placeholder. To use the Sum() function template The Sum() function is called the same way as normal functions are called. The example below shows a main() function using the Sum() function on different data types.
include <iostream> 
ifndef SUM_TEMPLATE_H 
define SUM_TEMPLATE_H 
template<class T> T Sum(T val1, T val2){ 
return val1 + val2;
} 
endif 
using namespace std; 
int main(){ 
cout<<Sum(3, 25)<<endl;//Integer
cout<<Sum(3.456, 5.786)<<endl; //Float
cout<<Sum('a', 'b')<<endl; //Char
//cout<<Sum(3, 3.5)<<endl; return 0; 
} 

Using Multiple Placeholders

The Sum() function template declared and defined in the above example used one type placeholder named T to reserve type spots in the function. Because both of the Sum() function’s parameters are reserved with the same placeholder they must be of the same type when the function is called. To illustrate, let us see what happens when the Sum() function is called with an integer and a float argument as shown in the following line of code:
cout<<Sum(3, 3.5)<<endl; 
Error : in function int main() line no 15: no matching function for call to `Sum(int, double) When the Sum() function template is called with two different argument types an error results. This error was produced using the Dev C++ 4.9.9.2. One way to eliminate this error is to declare the Sum() function template to use two different placeholders.
include <iostream> 
ifndef SUM_TEMPLATE_H 
define SUM_TEMPLATE_H 
template<class T, class U> T Sum(T val1, U val2){ 
 return val1 + val2;
}
endif 
using namespace std; 
int main(){ 
cout<<Sum(3, 25)<<endl;
cout<<Sum(3.456, 5.786)<<endl;
cout<<Sum('a', 'b')<<endl;
cout<<Sum(3, 3.5)<<endl;
return 0;
} 
Notice now there are two type placeholders declared on line 5 of the above example. T and U. The U placeholder is used for the second parameter in the Sum() function while the T placeholder is used for the first parameter and the return value. This will solve one problem but introduce another. The above Example shows the revised Sum() function template in use.
Refer to line 14 of the above example. Notice now that the Sum() function is called with the first argument an integer and the second argument a float. By using two placeholders in the function template the error produced by using two different argument types is eliminated. However, the result type of the Sum() function is dictated by the first argument type. Since the T placeholder is used to reserve the type spot for both the first parameter and the return type of the function, whatever type the first argument to the function happens to be will also be the return type of the function. In this example it is an integer. So, the result of calling the Sum() function with the arguments 3 and 3.5 is 6, not 6.5! Notice what happens when the order of the arguments are swapped.
To resolve the ambiguous return type issue simply declare yet another type place holder used specifically to dictate the function’s return type. The below example gives the revised Sum() function with the extra type placeholder V declared and used to reserve the return type.
include <iostream> 
ifndef SUM_TEMPLATE_H 
define SUM_TEMPLATE_H 
template<class T, class U, class V> V Sum(T val1, U val2){ 
return val1 + val2;
} 
endif 
using namespace std; 
int main(){ 
cout<<Sum<int, int, int>(3, 25)<<endl;
cout<<Sum<double, double, double>(3.456, 5.786)<<endl;
cout<<Sum<char, char, char>('a', 'b')<<endl;
cout<<Sum<double, int, double>(3.5, 3)<<endl;
return 0; }

Declaring And Using Class Templates

Class templates are used to declare and define a generic class structure. The compiler uses the class template and any types supplied via specialization to build a new class type. Let us begin the discussion of class templates with a simple Foo example. Example below shows the declaration and definition of a class template named Foo.
include <iostream> 
ifndef FOOTEMPLATEDEF_H 
define FOOTEMPLATEDEF_H 
template<class T> class Foo{ public: Foo(T _val); virtual ~Foo(); 
void setVal(T _val); T getVal(); private: T val; }; 
template<class T> Foo<T>::Foo(T _val):val(_val){} 
template<class T> Foo<T>::~Foo(){} 
template<class T> void Foo<T>::setVal(T _val){ val = _val; } 
template<class T> T Foo<T>::getVal(){ return val; } 
endif 
using namespace std; 
int main(){ 
Foo<int> f1(1); 
Foo<char> f2('d'); 
cout<<f1.getVal()<<endl; 
cout<<f2.getVal()<<endl; 
return 0; 
} 
The declaration of the Foo class templates begins on line 6 with the keyword template. There is only one template parameter declared named T. The T is used throughout the class declaration and definition to reserve a spot for the type declared when the Foo class is specialized. Referring to line 33 of above example, notice how the Foo class template is specialized to use an int type. The important point to note in this example is that Foo<int> and Foo<char> are two distinct types. A More Complex Class Template Example The below Example gives the source code for a template of the DynamicArray class.
include <iostream> 
ifndef _DYNAMIC_ARRAY_H 
define _DYNAMIC_ARRAY_H 
template<class T> class DynamicArray{ 
 public: DynamicArray(int _size = 5); 
 virtual ~DynamicArray(); 
 T& operator[](unsigned i); 
 int getSize(); 
 private: T* its_array; 
 int size; 
}; 
//////////////////////////////////////////////////////////
template<class T> DynamicArray<T>::DynamicArray(int _size):size(_size){ 
 its_array = new T[_size]; 
 for(int i=0; i<size; i++) its_array[i] = static_cast<T>(0); 
} 
template<class T> DynamicArray<T>::~DynamicArray(){ 
delete[] its_array; 
} 
template<class T> T& DynamicArray<T>::operator[](unsigned i){ 
 if(i >= (size))
 { 
      int newsize = size+10; 
  T* temp = new T[size]; 
  for(int j = 0; j<size; j++){ 
   temp[j] = its_array[j]; 
  } 
  delete[] its_array; 
  its_array = new T[newsize]; 
  for(int j = 0; j<size; j++){ 
   its_array[j] = temp[j]; 
  }
  for(int j=size; j<newsize; j++){ 
   its_array[j] = static_cast<T>(0); 
  }
  delete[] temp; 
  size = newsize; 
  return its_array[i]; 
 }
 else 
  return its_array[i]; 
} 
template<class T> int DynamicArray<T>::getSize(){ return size;} 
endif 
using namespace std; 
int main(){ 
 DynamicArray<char> d1; 
 DynamicArray<float> d2; 
 for(int i=0; i<6; i++){ 
  d1[i] = 'a'; 
 } 
 for(int i=0; i<6; i++){ 
  d2[i] = (i + .5); 
 } 
 for(int i=0; i<d1.getSize(); i++){ 
  cout<<d1[i]<<" "<<d2[i]<<endl; 
 } return 0; 
} 
Converting the DynamicArray class into a class template increased its usefulness as it can now be used to hold different types of objects, even user-defined types. The above example gives a main() function showing the DynamicArray class template in use.

Learn C++

Module 8 :Friend Functions

Introduction

Up to now you have learnt functions, classes, member functions. In this module you will learn about friend functions and its special features in C++.

Learning Objective


By the end of this module, you will able to:
  • Explain and use friend functions in C++ programs
  • Implement software objects as friends to one another

Friend

The concepts of encapsulation and data hiding dictate that nonmember functions should not be able to access an object’s private or protected data. The policy is, if you’re not a member, you can’t get in. However, there are situations where such rigid discrimination leads to considerable inconvenience. In order to access the non-public members of a class, C++ provides the friend facility. The accessibility of class members in various forms is shown in the below figure

See: https://docs.google.com/open?id=0B_cy2j6cIeqTSXotVGtwN19Jd3c

Friend Functions

Imagine that you want a function to operate on objects of two different classes. Perhaps the function will take objects of the two classes as arguments, and operate on their private data. In this situation there’s nothing like a friend function. Here’s a simple example, FRIEND that shows how friend functions can act as a bridge between two classes: <source lang = cpp> / friend.cpp // friend functions include <iostream> using namespace std; class beta; //needed for frifunc declaration //////////////////////////////////////////////////////////////// class alpha { private: int data; public: alpha() : data(3) { }
   //no-arg constructor 
friend int frifunc(alpha, beta); //friend function }; //////////////////////////////////////////////////////////////// class beta { private: int data; public: beta() : data(7) { } //no-arg constructor friend int frifunc(alpha, beta); //friend function }; //////////////////////////////////////////////////////////////// int frifunc(alpha a, beta b) //function definition { return( a.data + b.data ); }; //-------------------------------------------------------------- int main() { alpha aa; beta bb; cout << frifunc(aa, bb) << endl; //call the function return 0; } </source> In this program, the two classes are alpha and beta. The constructors in these classes initialize their single data items to fixed values (3 in alpha and 7 in beta). We want the function frifunc() to have access to both of these private data members, so we make it a friend function. It’s declared with the friend keyword in both classes: friend int frifunc(alpha, beta); This declaration can be placed anywhere in the class; it doesn’t matter whether it goes in the public or the private section. An object of each class is passed as an argument to the function frifunc(), and it accesses the private data member of both classes through these arguments. The function doesn’t do much: It adds the data items and returns the sum. The main() program calls this function and prints the result. A minor point: Remember that a class can’t be referred to until it has been declared. Class beta is referred to in the declaration of the function frifunc() in class alpha, so beta must be declared before alpha. Hence the declaration class beta; at the beginning of the program.

Friend Classes

The member functions of a class can all be made friends at the same time when you make the entire class a friend. The program FRICLASS shows how this looks.
// friclass.cpp 
include <iostream> 
using namespace std; //////////////////////////////////////////////////////////////// 
class alpha { 
 private: int data1; 
 public: alpha() : data1(99) { } //constructor 
 friend class beta; //beta is a friend class 
}; //////////////////////////////////////////////////////////////// 
class beta { //all member functions can access public, private data
 public: 
 private alpha data 
 void func1(alpha a) { cout << “\ndata1=” << a.data1; } 
 void func2(alpha a) { cout << “\ndata1=” << a.data1; } 
}; //////////////////////////////////////////////////////////////// 
int main() { 
 alpha a;
 beta b;
 b.func1(a);
 b.func2(a);
 cout << endl;
 return 0;
} 
In class alpha the entire class beta is proclaimed a friend. Now all the member functions of beta can access the private data of alpha (in this program, the single data item data1). Note that in the friend declaration we specify that beta is a class using the class keyword:
friend class beta; 
We could have also declared beta to be a class before the alpha class specifier, as in previous examples class beta; and then, within alpha, referred to beta without the class keyword:
friend beta; 

Learn C++

Module 8 :Friend Functions

Introduction

Up to now you have learnt functions, classes, member functions. In this module you will learn about friend functions and its special features in C++.

Learning Objective


By the end of this module, you will able to:
  • Explain and use friend functions in C++ programs
  • Implement software objects as friends to one another

Friend

The concepts of encapsulation and data hiding dictate that nonmember functions should not be able to access an object’s private or protected data. The policy is, if you’re not a member, you can’t get in. However, there are situations where such rigid discrimination leads to considerable inconvenience. In order to access the non-public members of a class, C++ provides the friend facility. The accessibility of class members in various forms is shown in the below figure

See: https://docs.google.com/open?id=0B_cy2j6cIeqTSXotVGtwN19Jd3c

Friend Functions

Imagine that you want a function to operate on objects of two different classes. Perhaps the function will take objects of the two classes as arguments, and operate on their private data. In this situation there’s nothing like a friend function. Here’s a simple example, FRIEND that shows how friend functions can act as a bridge between two classes: <source lang = cpp> / friend.cpp // friend functions include <iostream> using namespace std; class beta; //needed for frifunc declaration //////////////////////////////////////////////////////////////// class alpha { private: int data; public: alpha() : data(3) { }
   //no-arg constructor 
friend int frifunc(alpha, beta); //friend function }; //////////////////////////////////////////////////////////////// class beta { private: int data; public: beta() : data(7) { } //no-arg constructor friend int frifunc(alpha, beta); //friend function }; //////////////////////////////////////////////////////////////// int frifunc(alpha a, beta b) //function definition { return( a.data + b.data ); }; //-------------------------------------------------------------- int main() { alpha aa; beta bb; cout << frifunc(aa, bb) << endl; //call the function return 0; } </source> In this program, the two classes are alpha and beta. The constructors in these classes initialize their single data items to fixed values (3 in alpha and 7 in beta). We want the function frifunc() to have access to both of these private data members, so we make it a friend function. It’s declared with the friend keyword in both classes: friend int frifunc(alpha, beta); This declaration can be placed anywhere in the class; it doesn’t matter whether it goes in the public or the private section. An object of each class is passed as an argument to the function frifunc(), and it accesses the private data member of both classes through these arguments. The function doesn’t do much: It adds the data items and returns the sum. The main() program calls this function and prints the result. A minor point: Remember that a class can’t be referred to until it has been declared. Class beta is referred to in the declaration of the function frifunc() in class alpha, so beta must be declared before alpha. Hence the declaration class beta; at the beginning of the program.

Friend Classes

The member functions of a class can all be made friends at the same time when you make the entire class a friend. The program FRICLASS shows how this looks.
// friclass.cpp 
include <iostream> 
using namespace std; //////////////////////////////////////////////////////////////// 
class alpha { 
 private: int data1; 
 public: alpha() : data1(99) { } //constructor 
 friend class beta; //beta is a friend class 
}; //////////////////////////////////////////////////////////////// 
class beta { //all member functions can access public, private data
 public: 
 private alpha data 
 void func1(alpha a) { cout << “\ndata1=” << a.data1; } 
 void func2(alpha a) { cout << “\ndata1=” << a.data1; } 
}; //////////////////////////////////////////////////////////////// 
int main() { 
 alpha a;
 beta b;
 b.func1(a);
 b.func2(a);
 cout << endl;
 return 0;
} 
In class alpha the entire class beta is proclaimed a friend. Now all the member functions of beta can access the private data of alpha (in this program, the single data item data1). Note that in the friend declaration we specify that beta is a class using the class keyword:
friend class beta; 
We could have also declared beta to be a class before the alpha class specifier, as in previous examples class beta; and then, within alpha, referred to beta without the class keyword:
friend beta; 

Learn C++

Module 6 :Multiple Inheritance

Introduction

We have seen Inheritance in previous module. In C++, it also possible that a single derived class can have multiple base classes. This means a class can acquire properties of multiple classes. This module explains you about the multiple inheritance in C++.

Learning Objective


By the end of this Module, you will be able to:
  • Understand the concept of multiple inheritance
  • Identify and solve the ambiguities that arise in multiple inheritance.
  • Define Virtual base class
  • State the order of invocation of constructors and destructors

Multiple Inheritance

Multiple Inheritance is the concept where a subclass inherits properties from multiple base classes. A familiar example of multiple inheritance is the child inheriting the characteristics of the parents.
See: https://docs.google.com/open?id=0B_cy2j6cIeqTVWVuTzk2YnNpUEU
In the following example, classes A, B, and C are direct base classes for the derived class X: The following inheritance graph describes the inheritance relationships of the above example. An arrow points to the direct base class of the class at the tail of the arrow: <source lang = cpp> class A { /* ... */ }; class B { /* ... */ }; class C { /* ... */ }; class X : public A, private B, public C { /* ... */ }; </source>
See: https://docs.google.com/open?id=0B_cy2j6cIeqTaVA0TzItTEZtQlE

Ambiguities in Multiple Inheritance

When a class inherits from multiple base classes, a whole lot of ambiguities creep in. For example, what happens when two base classes contain a function of the same name?
For example given below --> Class A, Class B has a member function named disp() (to display the attributes of the class) and Class C inherits A and B. <source lang = cpp> class A {
 /* ... */
 public: 
 void disp(void); 
 };
class B {
/* ... */
public:
 void disp(void);
}; class C : public A, private B { /* ... */ }; void main(){
C c;
C.disp();//Ambiguous
} </source> Here the reference to disp() is ambiguous because the compiler does not know whether disp() refers to the member in class base1 or base2. This ambiguity can be resolved using the scope resolution operator as illustrated hereunder. <source lang = cpp> class C : public A, private B { /* ... */ public:
  void disp(void){
     A.disp();
     B.disp();
  } 
}; void main(){
C c;
c.disp();  
} This ambiguity can also be resolved by overriding as illustrated hereunder. void main(){
C c;
c.A::disp();
c.B.::disp();
} </source> Another ambiguity that arises in multiple inheritance is the possibility of the derived class having multiple copies of the same base class. Consider the following diagram.

See: https://docs.google.com/open?id=0B_cy2j6cIeqTODhVU3pyazd0UUU
<source lang = cpp> class L { /* ... */ }; // indirect base class class B2 : public L { /* ... */ }; class B3 : public L { /* ... */ }; class D : public B2, public B3 { /* ... */ }; // valid </source> In the above example, class D inherits the indirect base class L once through class B2 and once through class B3. However, this may lead to ambiguities because two objects of class L exist, and both are accessible through class D. You can avoid this ambiguity by referring to class L using a qualified class name. For example:
B2::L
or
B3::L
You can also avoid this ambiguity by using the base specifier virtual to declare a base class.

Virtual Base Classes

The principle behind virtual base classes is very simple. When the same class is inherited more than once via multiple paths, multiple copies of the base class members are created in memory. By declaring the base class inheritance as virtual, only one copy of the base class is inherited. A base class inheritance can be specified as virtual using virutal qualifier.
The class definitions would be modified as follows <source lang = cpp> class L { /* ... */ }; // indirect base class class B1 : virtual public L { /* ... */ }; class B2 : virtual public L { /* ... */ }; class D : public B1, public B2 { /* ... */ }; // valid </source> Invocation of Constructors and Destructors
  • Constructors are invoked in the following order:
    • Virtual base class constructors -- in the order of inheritance.
    • Non-Virtual base class constructors -- in the order of inheritance.
    • Member objects constructors -- in the order of declaration
    • Derived class constructor.
  • Destructor are invoked in the reverse order

Resources


Learn C++

Module 5 :Inheritance

Introduction

In previous modules you have worked with classes and some cool features of C++ like method and operator overloading. This module explains about the Inheritance concept of OOP. The idea of classes leads to the idea of Inheritance. In our daily lives, we can see many things divided into sub classes; let us say the class of animals is divided into mammals, insects, birds and so on. The principle in this sort of division is that each subclass shares some common characteristics from which it’s derived. In a similar way, an OOP class can be used as the basis for one or more different subclasses.

Learning Objective

At the end of this module, you will be able to:
  • Understand the implementation of inheritance in C++
  • Override the base class members
  • Access overridden base class members using the scope resolution operator
  • Understand the concept of base class initialization

Inheritance

The philosophy behind inheritance is to portray things as they exist in the real world. As inheritance is found in real world, it is important feature of OO programming. Inheritance has many advantages, the most important of them being the reusability of code. Once a class is created, it can be used to create new subclasses. The reuse of existing class saves time and effort.
The Class from which another class is derived is called the base class. The class which inherits the properties of the base class is called the derived class. Each instance of the derived class includes all the members of the base class. Since the derived class inherits all properties of the base class, the derived class has a larger set of properties than its base class. However, the derived class may override some or all the properties of the base class.
In C++, any class can be a base class. More than one class can be derived from a single base class, and a derived class can be a base class to another. if class d1 is inherited from class b1, then the syntax for declaring class derived is
class d1:public b1 
An object defined outside the class can access only the public members of the class. Therefore, private members of a class cannot be directly accessed from outside the class. This holds true even for a derived class. Even though the derived class inherits all the members’ data and functions from the base class, private members of the base class are not directly accessible from the derived class. The idea behind this is never to compromise on encapsulation implemented through data hiding.
The protected members of a class can be accessed by its member’s functions, or within any class derived from it. Protected members behave like public members with respect to the derived class and like private members with respect to the rest of the program.

Overriding Base Class Members

A base class member can be overridden by defining a derived class member with the same name as that of the base class member.
If the function exists in both the derived class and the base class then:
  • If the function is invoked from an Object of the derived class, then the function in the derived class is executed.
  • If the function is invoked from an Object of the base class, then the base class member function is invoked.

Inheritance Example in Real World

In a Banking System, Manager, Officers, Clerk have some common and as well as special behavior (specific tasks/actions). The commonality is that they are all employees of the Bank. A generalized class “Employee_GeneralizedClass” could be used to represent the commonality among Object classes. The generalization is often referred to as inheritance, and the generalized class as parent class. Inheritance is a means of specifying hierarchical relationships between object classes.
Points to Remember
  • The class from which a subclass is derived is referred to as the base class'.
  • Base class constructors and destructors are not inherited by the derived class.
  • Derived class constructors must explicitly call the base class constructors with appropriate parameters.
  • Destructors are invoked in the reverse order.

Resources

Walk Through Video (here)
PPT:
Inheritance:
Protected:

Learn C++

Module 4 :Classes and Objects (Contd..)

Learning Objective


Objective is to better understand
  1. Constructor
  2. Destructor
  3. Operator Overloading
  4. Dynamic Memory Allocation
and also gain additional practice with classes

Resources


Learn C++

Classes and Objects

Introduction

In previous module you have created basic programs using classes. This module enhances your learning to the classes in detailed. Apart from Classes this module also covers the topics constructor, copy constructor, destructor, function overloading and operator overloading.

Learning Objective

On successful completion of this module you should be able to:
  • Explain the purpose of a class constructor and identify a default constructor for a class
  • Explain the purpose of a class destructor and identify a default destructor for a class
  • Apply function overloading
  • Apply operator overloading
  • Code and use simple C++ classes using the following facilities:
    • public member functions and private data members
    • one or more constructors, including where appropriate, a default constructor
    • Overloading of functions
    • Operator overloading

The Class

In OOP, objects are instances of classes. What does this mean? Let’s look at an analogy. Almost all computer languages have built in data types like int, float, double, char etc… For example we take int. As you know you can declare as many variables of type int as you need in your program. <source lang = cpp> int age; int day; int count; </source>
In addition, class also provides security to the program data; there are three levels of Access Modifiers, which are associated with the class. The members (data or functions) can be declared to be:
  • Private members of the class are hidden and can be accessed only with in the class. Access to them members is denied from outside the class
  • Protected members are accessible within the class and to the derived class(to be covered in next modules)
  • Public members are visible outside the class and can be accessed from anywhere within the program.
A class looks just like a structure, and indeed they are almost equivalent. By convention we always use class for abstract data types and only use structure for ‘ordinary data structures’ that don’t have member functions. The only difference between a structure and a class is that structure members have public access by default and class members have private access by default, you can use the keywords class or struct to define equivalent classes.

The Class Scope

Every class defines the scope for the members in it. The data members of a class may be defined, before they are used in a member functions, or can be used in the member functions, and may be defined later in the class. The data members have the class scope, immaterial of where they are defined in the class.
Resources

Constructor

A constructor is a special member function that has the same name as the class. The constructor will be called automatically whenever an object is created. It could contain initializations to the variables of the object or calling other functions etc. The constructor by nature cannot return any value. The return has to be void. It can however take an argument list. The constructor which takes no arguments is called the default constructor. The constructor can be defined within the class definition or outside of it, just as any other member function definition. It can also be defined outside the class and made inline, just as other member functions.

Copy constructor

A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object. First argument of such constructor is a reference to an object of the same type as being constructed (const or non-const), which might be followed by parameters of any type (all having default values). Normally the compiler automatically creates a copy constructor for each class (known as an implicit copy constructor) but for special cases the programmer creates the copy constructor, known as an explicit copy constructor. In such cases, the compiler doesn't create one.

Destructor

The destructor destroys a previously created object. The destructor takes no arguments and cannot return a value. The destructor has the same name as of the class, except that the name is preceded by a ~ (tilda).

Composite Class

A Composite object can be defined as one which consists of other objects. As an example, consider the class Circle as composite object containing an instance of Point, representing the centre and radius which is of type, float. The definition of Point and Circle in this case would be. <source lang="cpp">
class Point{ 
 float x;
 float y;
}; 
class Circle{ 
 float radius;
 Point centre;
}; </source>

Pass by value and Pass by reference

In the parameter passed to the copy constructor, you would notice an ampersand (&). Recall that in C, you can only pass parameters by value and not by reference. C++ enables you to pass parameters by reference. To do so, use an ampersand (&) before the name of the parameter in the parameter declaration.

Function Overloading

One really nice and cool feature in C++ over C is Function Overloading. This means that you can use the same name for different functions. Yes you could. For example, have three functions all named sum(), but each one would have a separate function definitions or return types. It may not seem obvious why you would want to do this, because you may need to sum two or more integers and floating type values in the same program. So these feature so helpful in that case.
Overloading constructor: When constructor is overloaded, the constructor must vary in the argument list. Upon object creation, that constructor for which there is match between the formal and the actual parameters is invoked.

Operator Overloading

You have seen how functions can be overloaded in C++, it also possible to overload the built in C++ operators such as +, -, >=, and ++ so that they could invoke different functions, depending on their operands. For example, the + in a+b will call a function if a and b are integers, but will call different function if a and b are strings or objects of a class you have created. Go through the given urls below to learn more about operator overloading.

The keyword this

The keyword this represents a pointer to the object whose member function is being executed. It is a pointer to the object itself. One of its uses can be to check if a parameter passed to a member function is the object itself.