Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Overloading [] Operator II

In the previous article Overloading
[] Operator
, we overloaded the [] operator in a class to access data
within the class by indexing method.


The operator [] function was defined as below:


  int myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

As you can see, the above operator
function
is returning values, hence it could only be used on the right
hand side of a statement. It’s a limitation!


You very well know that a statement like below is very common with respect
to arrays:


a[1]=10;


But as I said, the way we overloaded the [] operator, statement like the one
above is not possible. The good news is, it is very easy to achieve this.


For this we need to overload the [] operator like this:


  int &myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

By returning a reference
to the particular element, it is possible to use the index expression on the
left hand side of the statement too.


The following program illustrates this:



// Example Program illustrating
// the overloading of [] operator
// ----
// now the index expression can be
// used on the left side too
#include <iostream.h>

class myclass
{
// stores the number of element
int num;
// stores the elements
int a[10];

public:
myclass(int num);

int &operator[](int);
};

// takes the number of element
// to be entered.(<=10)
myclass::myclass(int n)
{
num=n;
for(int i=0;i<num;i++)
{
cout<<"Enter value for element "<<i+1<<":";
cin>>a[i];
}
}

// returns a reference
int &myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

void main()
{
myclass a(2);

cout<<a[0]<<endl;
cout<<a[1]<<endl;

// indexing expression on the
// left-hand side

a[1]=21;
cout<<a[1];
}


Related Articles:


Overloading [] Operator

Have a look at the following code fragment:


  myclass a(3);

cout<<a[0];

Doesn’t it look awkward!


Yes it does, because we have overloaded he [] operator and given it some special
meaning.


In C++, it is possible to overload the [] operator
and give it a different meaning
rather then the usual object indexing.


The general form for overloading [] operator is:


  ret-type operator[](int);

It is considered a binary operator hence when declared as a member, it accepts
one explicit argument (usually int).


Although you are free to accept any type of argument but sticking to the original
concept of indexing, it would always be an integer.


ob[i];


When the compiler encounters the above expression (with the [] operator overloaded)
the [] operator
function
is called as below:


ob.operator[] (1)


The argument ‘1’ is passed explicitly while ‘ob’ is
passed implicitly using the ‘this’
pointer.


Enough discussion, now lets get on to some action!


Below is the example program illustrating the overloading of [] operator:



// Example Program illustrating
// the overloading of [] operator
#include <iostream.h>

class myclass
{
// stores the number of element
int num;
// stores the elements
int a[10];

public:
myclass(int num);

int operator[](int);
};

// takes the number of element
// wished to be entered.(<=10)
myclass::myclass(int n)
{
num=n;
for(int i=0;i<num;i++)
{
cout<<"Enter value for element "<<i+1<<":";
cin>>a[i];
}
}

int myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];

// else
return NULL;
}

void main()
{
myclass a(3);

cout<<a[0]<<endl;
cout<<a[2]<<endl;

// out of bound
cout<<a[3]<<endl;
}


Related Articles:


Adding Flexibility to Operators while Overloading them

  class_name class_name::operator+(int x)
{
class_name temp;

temp.a = a + x;
temp.b = b + x;

return temp;
}


With reference to the above operator
function
and supposing that ‘ob’ is an object of the class
to which this function belongs; Is the statement below legal:


ob2 = ob1 + 100;


Yes, but what about the following statement:


ob2 = 100 + ob1;


Surely this won’t work!


100 is an integer constant and has no ‘+’ operator that could add
it with user-defined types (object ‘ob’).


This certainly is a shortcoming, since often we don’t really care which
operand is where (as in addition and multiplication) and we order the operands
as necessary (as in subtraction and division).


To overcome this we can overload two-two versions of these operators
as friend
, one for ‘integer + object’ type and the other
for ‘object + integer’ type.


So, for example for addition we have to overload the ‘+’ operator
twice as below:


  friend class_name operator+(class_name,int);
friend class_name operator+(int,class_name);

Similarly we have to overload other operators.


The program below illustrates this concept:



// Program to illustrate
// the overloading of
// flexible addition
// and subtraction
// operators
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// object + int form
friend myclass operator+(myclass,int);
friend myclass operator-(myclass,int);

// int + object form
friend myclass operator+(int,myclass);
friend myclass operator-(int,myclass);
};

myclass operator+(myclass ob,int x)
{
myclass temp;

temp.a = ob.a + x;
temp.b = ob.b + x;

return temp;
}

myclass operator-(myclass ob, int x)
{
myclass temp;

temp.a = ob.a - x;
temp.b = ob.b - x;

return temp;
}

myclass operator+(int x, myclass ob)
{
// does the same thing
// because in addition
// it doesn't matters
// which operand is where
myclass temp;

temp.a = x + ob.a;
temp.b = x + ob.b;

return temp;
}

myclass operator-(int x, myclass ob)
{
myclass temp;

temp.a = x - ob.a;
temp.b = x - ob.b;

return temp;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a=a + 10;
a.show();

b=100 + b;
b.show();
}


Related Articles:


Overloading the Short-Hand Operators (+= and -=) using Friend Functions

In this article we’re going to overload the shorthand
addition (+=) and subtraction (-=) operators
using friend
functions.


As you can observe in the program below, the operator functions are taking
the first argument (operand) as a reference
(call by reference). This is due the fact that these operators need to alter
the data of the actual operand itself.


This is similar to the case of increment/decrement
operators
(click for detailed information).



// Overloading the shorthand
// += and -= operators using
// friend functions
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// declared as friend
friend myclass operator+=(myclass&, myclass);
friend myclass operator-=(myclass&, myclass);
};


myclass operator+=(myclass &ob1, myclass ob2 )
{
// data of the first operand
// are to be changed, so accepting
// it as a reference
ob1.a+=ob2.a;
ob1.b+=ob2.b;

return ob1;
}

myclass operator-=(myclass &ob1, myclass ob2 )
{
ob1.a-=ob2.a;
ob1.b-=ob2.b;

return ob1;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a+=b;
b+=a;

a.show();
b.show();
}


Related Articles:


Overloading Post-Fix Forms of ++ and -- Operators using Friend Functions

From the article Overloading
Post-Fix Forms of ++ and -- Operators
, we know that the postfix form
of the increment/decrement operator function takes two arguments, one is passed
implicitly
and the other as usual.


Its general form is:


  ret-type operator++(int);

As we know that when we overload operators as friends,
all the operands (arguments) are passed explicitly.


So, the general form for overloading postfix form of
increment/decrement operators
using friend functions should be (and
it really is) like this:


  ret-type operator++(class-name&, int);

Where the second int(eger) argument, as you know is a dummy variable and has
no use.


The following program illustrates this:



// Program to illustrate the overloading
// of increment / decrement operators
// as friends
// Overloads both prefix and postfix
// form
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// prefix form
friend myclass operator++(myclass&);
friend myclass operator--(myclass&);

// postfix form
friend myclass operator++(myclass&, int);
friend myclass operator--(myclass&, int);

};

// ---- PREFIX FORM ----
myclass operator++(myclass &ob)
{
ob.a++;
ob.b++;

return ob;
}

myclass operator--(myclass &ob)
{
ob.a--;
ob.b--;

return ob;
}
// ---- PREFIX FORM ENDS ----

// ---- POSTFIX FORM ----
myclass operator++(myclass &ob, int x)
{
myclass temp;
temp=ob;

ob.a++;
ob.b++;

return temp;
}

myclass operator--(myclass &ob, int x)
{
myclass temp;
temp=ob;

ob.a--;
ob.b--;

return temp;
}
// ---- POSTFIX FORM ENDS ----

void main()
{
myclass a(10,20);
myclass b(100,200);

++a;
(b++).show();
b.show();

a.show();
b.show();

a=b++;

a.show();
b.show();
}


Related Articles:


Overloading Increment/Decrement Operators using Friend Functions

In the article Operator
Overloading using Friend Functions
, we saw how we can overload simple
operators using friend functions, in the other article Overloading
Increment/Decrement Operators
, we saw the method of overloading increment/decrement
operators as member functions. Combining both these, we’ll try to overload
the increment/decrement operators using friend
functions
, in this article.


As we know there are some differences in overloading operators as a friend.


Increment/decrement are the type of operators that need to change the operands
itself. In the case of operator overloading as member functions, ‘this’
pointer
was passed so any change done would result in the operand itself
getting changed. But in the case of friend functions, operands are passed explicitly
and that also as call by value, hence it is impossible to change the operand
that way.


Let’s take an example, suppose we have an object ‘ob’of a
class say 'myclass' which overloads the increment operator,


  ob++;

This statement would result in a call to the overloaded increment (++) operator
function, which could be something like the one below:


  myclass operator++()
{

a++;
b++;

return *this;
}

Supposing the data of the class we need to alter are a and b, the above statement
would increment the data of the object that generated the call, hence the desired
result is achieved.


Had the function been overloaded as a friend something like this:


  myclass operator++(myclass ob)
{
ob.a++;
ob.b++;

return ob;
}


Then the operand’s copy (not the actual object that generated the call)
would have been passed to the function and any change (a++ and b++) would only
have incremented the data of the copy of the object passed (call by value) and
the data of the operand would have remained unchanged.


To overcome this we need to accept the reference
of the object (call by reference) as the argument to overload the operators
as a friend.


The following program illustrates this method:



// Program to illustrate the overloading
// of increment / decrement operators
// as friends
// NOTE: Prefix form is overloaded here
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// accepting references
friend myclass operator++(myclass&);
friend myclass operator--(myclass&);

};

myclass operator++(myclass &ob)
{
ob.a++;
ob.b++;

return ob;
}

myclass operator--(myclass &ob)
{
ob.a--;
ob.b--;

return ob;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

++a;
++b;

a.show();
b.show();

a=--b;

a.show();
b.show();
}


Related Articles:


Practical Example of Using Virtual Functions II

From the past few articles we have been discussing about Virtual
Functions.
Before taking up another topic for discussion I thought
of providing one more example of how and when virtual functions may be used.
So, here it is, a practical
example of virtual function.


As virtual functions and Run-Time
Polymorphism
goes hand-in-hand so the example here may also serve as
an example of the use of run-time polymorphism.



// Example to illustrate
// the use of virtual functions
// and run-time polymorphism
#include <iostream.h>

// -- SORT CLASS --
class sort
{
protected:
int *arr;
int num_elmnt;

public:
sort(int);
~sort();
void get_elmnt();
void show_elmnt();
virtual void do_sorting()=0;
};

// takes an argument
// which is the number of
// elements we want
sort::sort(int x)
{
num_elmnt=x;
arr=new int[num_elmnt];
}

sort::~sort()
{
// free up he allocated memory
delete []arr;
}

void sort::get_elmnt()
{
// input elements
cout<<"\nEnter Elements...";
for(int i=0;i<num_elmnt;i++)
{
cout<<"\n#"<<i+1<<":";
cin>>arr[i];
}
}

void sort::show_elmnt()
{
// display the elements
cout<<"\nElements are...";
for(int i=0;i<num_elmnt;i++)
{
cout<<"\n#"<<i+1<<":";
cout<<arr[i];
}
}
// -- SORT CLASS ENDS --

// -- BUBBLE SORT CLASS --
class bubble_sort : public sort
{
public:
// constructor only calls the
// base constructor with the
// parameter
bubble_sort(int x):sort(x){}

void do_sorting();
};

void bubble_sort::do_sorting()
{
int temp;

// do bubble sorting
for(int i=0;i<num_elmnt;i++)
for(int j=0; j<(num_elmnt-1); j++)
if (arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
// -- BUBBLE SORT CLASS ENDS --

// -- SELECTION SORT CLASS --
class selctn_sort : public sort
{
public:
// just call the base class
// constructor
selctn_sort(int x):sort(x){}
void do_sorting();
};

void selctn_sort::do_sorting()
{
int temp;

// do selection sorting
for(int i=0;i<(num_elmnt-1);i++)
for(int j=i+1;j<num_elmnt;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
};
// -- SELECTION SORT CLASS ENDS --

void main()
{
bubble_sort bubble(3);
selctn_sort selctn(5);
sort *ptr;

ptr=&bubble;
ptr->get_elmnt();
ptr->do_sorting();

ptr=&selctn;
ptr->get_elmnt();
ptr->do_sorting();

// again point to bubble
ptr=&bubble;
ptr->show_elmnt();

// again point to selctn
ptr=&selctn;
ptr->show_elmnt();
}


Related Articles:


Properties of Pure Virtual Functions

In the article Properties
of Virtual Functions
, we discussed about two properties of virtual
functions in detail. In this article we’ll be discussing about some properties
of Pure
Virtual Functions.


Property #1: We know that a
base class can’t define a pure virtual function and at the same time its
derived class must define it. But what if the derived class is used as base
for deriving yet another class; is this possible?


Yes, it is, as is obvious from the following program:



#include <iostream.h>

// base class
class base
{
public:
// pure virtual function
// declaration
virtual void func() = 0;
};

// derived class
class derived1 : public base
{
public:
// must define
void func()
{
cout<<"Derived1's func()\n";
}
};

// derived from class derived1
class derived2 : public derived1
{
public:
void func()
{
cout<<"Derived2's func()\n";
}
};

// main
void main()
{
derived1 d1;
derived2 d2;

d1.func();
d2.func();
}


Hence strictly speaking, a pure virtual function cannot be declared and defined
in the same class.


Property #2: While it’s
necessary for a derived class to override a pure virtual function but if we
derive yet another class from that derived class then it’s not necessary
for the newly derived class to override that function.


So that means, if we have a hierarchy of derived classes then a pure virtual
function must be overridden at least once.


It is clear from the following program:



#include <iostream.h>

// base class
class base
{
public:
// pure virtual function
// declaration
virtual void func() = 0;
};

// derived class
class derived1 : public base
{
public:
// must define
void func()
{
cout<<"Derived1's func()\n";
}
};

// derived from class derived1
class derived2 : public derived1
{
public:
// may not override the
// pure virtual function
};

// main
void main()
{
derived1 d1;
derived2 d2;

d1.func();

// derived1's function will
// be called
d2.func();
}


Property #3: We know that we
can’t declare objects of Abstract
Classes
but since C++ offers very powerful Polymorphism
capability, we can have their pointer (as well as references).


It is clear from the following program:



#include <iostream.h>

// base class
class base
{
public:
// pure virtual function
// declaration
virtual void func() = 0;
};

// derived class
class derived1 : public base
{
public:
// must define
void func()
{
cout<<"Derived1's func()\n";
}
};

// derived from class derived1
class derived2 : public derived1
{
public:
void func()
{
cout<<"Derived2's func()\n";
}
};

// main
void main()
{
// although objects of abstract classes
// cannot be declared but we can have
// their pointers
base *bptr;

derived1 d1;
derived2 d2;

// point to derived1 's object
bptr=&d1;

// derived1's func will be called
bptr->func();

// point to derived2's object
bptr=&d2;

// derived2's func will be called
// same interface is used
// but different function
// is called
bptr->func();
}


Related Articles:


Practical Example of Using Virtual Functions

From the past few articles we have been discussing about virtual functions
but we are yet to observe any of its practical use, this article would do that!


In this article we are going to show you a very simple program that illustrates
the practical use of virtual functions.


Please read the code carefully!



// Practical example of
// when virtual functions are
// used
#include <iostream.h>

class area
{
protected:
int mag;
double a;

public:
area(int x){mag=x;}
double get_area(){return a;}

// pure virtual function
virtual void compute()=0;
// it is made pure as
// it couldn't have any meaningful
// definition since area can only
// be defined w.r.t something specific
};

class circle_area : public area
{
public:
circle_area(int x) : area(x){}

// now that we are referring
// to area w.r.t a circle so
// it is natural that we define
// it
void compute()
{
a=(mag*mag)*3.14;
}
};

class square_area : public area
{
public:
square_area(int x) : area(x){}

// same for this!
void compute()
{
a=mag*mag;
}
};

void main()
{
square_area sa(10);
circle_area ca(20);

sa.compute();
ca.compute();

cout<<"Area of square: "<<sa.get_area();
cout<<endl;
cout<<"Area of cirlce: "<<ca.get_area();
}


Related Articles:


Pure Virtual Functions

From the previous article Properties
of Virtual Functions
, we know that a virtual function may or may not
be overridden in the derived lasses. It means, it is not necessary for a derived
class to override a virtual function.


But there are times when a base class is not able to define anything meaningful
for the virtual function in that case every derived class must provide its own
definition of the that function. To force this type of overriding you use the
following general form to declare a virtual function:



virtual ret-type func-name(arg-list)=0;


This type of virtual function is known as Pure Virtual Function.


There are two major differences between a virtual and a pure virtual function,
these are below:




  • There CAN’T be a definition of the pure virtual function in the base
    class.




  • There MUST be a definition of the pure virtual function in the derived
    class.




By making a virtual function ‘Pure’, it becomes necessary for the
derived classes to override it, further since the base class can’t define
a pure virtual function, we can’t have objects of that class. These types
of incomplete classes (having one or more pure virtual function) are known as
Abstract Classes and are used extensively.


The following program illustrates this:



// Pure Virtual Functions
#include <iostream.h>

// base class
class base
{
public:
// pure virtaul function
// declaration
virtual void func() = 0;
// can't define
};

// derived class
class derived : public base
{
public:
// must define
void func()
{
cout<<"Derived1's func()\n";
}
};

// main
void main()
{
// --CODE: base b
// won't work because we
// can't have objects of
// absract classes
derived d1;

d1.func();
}


Related Articles:


Properties of Virtual Functions

From the previous two articles Introduction
to Virtual Functions
and Virtual
Functions and Run-time Polymorphism
, we have been discussing about
Virtual Functions.


In this article we’ll be discussing about two important properties of
Virtual Functions.


As properties can be better understood by examples, we’ll be using them
more rather than text and definitions that could confuse you.


Property #1:



// Properties of virtual functions
#include <iostream.h>

// base class
class base
{
public:
virtual void func()
{
cout<<"Base's func()\n";
}
};

// derived class
class derived1:public base
{
public:
// this is a virtual function
void func()
{
cout<<"Derived1's func()\n";
}
};

// derived from another
// derived class
class derived2:public derived1
{
public:
// still virtual
void func()
{
cout<<"Derived2's func()\n";
}
};

// main
void main()
{
base b;
derived1 d1;
derived2 d2;

b.func();
d1.func();
d2.func();
}


OUTPUT:

Base's func()
Derived1's func()
Derived2's func()

The code above illustrates that when a class is derived from another derived
class (which has inherited a virtual function from its base class) then also
the virtual function can be overridden. So, it means that once declared virtual,
a function (no matter how many times inherited in hierarchy) still remains Virtual
and hence can be overridden.


Property #2: This is an extension
of the previous property, as you know that a virtual function remains virtual
no matter how many times it is inherited in a hierarchy, but what if one of
the derived class doesn’t overrides it, what will happen then? The following
code answers this!



// Properties of virtual functions
#include <iostream.h>

// base class
class base
{
public:
virtual void func()
{
cout<<"Base's func()\n";
}
};

// derived class
class derived1:public base
{
public:
// this is a virtual function
void func()
{
cout<<"Derived1's func()\n";
}
};

// derived from another
// derived class
class derived2:public derived1
{
public:
// no overriding
};

// another derived class
class derived3:public derived2
{
public:
// can still be overridden
void func()
{
cout<<"Derived3's func()\n";
}
};

// main
void main()
{
base b;
derived1 d1;
derived2 d2;
derived3 d3;

b.func();
d1.func();

// will call the function overridden
// by its base class because it didn't
// override the function
d2.func();

d3.func();
}


OUTPUT:

Base's func()
Derived1's func()
Derived1's func()
Derived3's func()

The above code is pretty much self-explanatory so I don’t think it needs
further explanations.


Related Articles:


Virtual Functions and Run-time Polymorphism

Before beginning this I would like to tell you one thing through the following
program:



// Virtual Functions and
// Run-time Polymorphism
#include <iostream.h>

// base class
class base
{
public:
int a;
};

// derived class
class derived:public base
{
public:
int b;
};

// main
void main()
{
base b;
derived d;

// base class pointer
base *bptr;

// pointer pointing
// to base's object
bptr=&b;

bptr->a=10;

// pointer pointing
// to derived's object
bptr=&d;

// still is able to access
// the members of the base
// class
bptr->a=100;
}


The property above combined with virtual function can be used to achieve a
very special and powerful feature, known as run-time polymorphism.


We had discussed about What
is Polymorphism
before so we wont be discussing it here.


The program below illustrates how virtual functions can be used to achieve
run-time polymorphism.


Please read the code carefully so that you understand how it’s working.



// Using Virtual functions to
// achieve run-time Polymorphism
#include <iostream.h>

// base class
class base
{
public:
virtual void func()
{
cout<<"Base's func()\n";
}
};

// derived class
class derived:public base
{
public:
void func()
{
cout<<"Derived's func()\n";
}
};

// main
void main()
{
int ch=0;

base b;
derived d;

// base class pointer
base *bptr;

while(ch!=3)
{
cout<<"1> Call Base's func\n";
cout<<"2> Call Derived's func\n";
cout<<"3> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
// point to base's object
bptr=&b;
break;

case 2:
// point tp derived's object
bptr=&d;
break;

default:
bptr=&b;
}

// call whichever function
// user has chosen to call
bptr->func();
}
}


Related Articles:


Introduction to Virtual Functions

Virtual functions are special member functions of a class which may be re-defined
in the derived classes. It is used to give specific meaning to the base class
member function with respect to the derive class.


Virtual functions can be thought of as a function name reserved in the bas
class which may be re-defined in the derived classes as per the need so that
every derived class has the same function that performs specific (as redefined
in the derived class) action.


Let’s now have a look at a simple program to show virtual functions inaction:



// Virtual functions
#include <iostream.h>

// base class
class base
{
public:
// precede the function name
// with the 'virtual' keyword
// to make it a virtual function
virtual void func()
{
cout<<"Base's func()\n";
}
};

// derived class
class derived:public base
{
public:
// redefinition of the
// function
void func()
{
cout<<"Derived's func()\n";
}
};

// main
void main()
{
base b;
derived d;

// notice that both are calling
// the same function but different
// functions gets called as per
// the class to which the object
// belongs to
b.func();
d.func();
}


OUTPUT:


  Base's func()
Derived's func()


The redefinition of the virtual function in the derived class is known
as overriding





As you can see there is nothing confusing, the virtual function is a general
member function and is defined as such, only difference being that it’s
preceded by the virtual keyword that gives it the special property.


NOTE: By redefining a virtual function, all its previous meaning (as was defined
in the base class) is lost.


As in the example program the base class defines the virtual function to print
“Base's func()” and the derived class overrides it to print “Derived's
func()”. So when we call the overridden function it only prints what was
defined in the redefinition hence the original meaning of the function is lost.


Related Articles:


Friend Functions of Class

First, have a look at the following code:



// Using Friend Functions
#include <iostream.h>

class myclass
{
int a;

public:
friend int geta(myclass);
void seta(int x){a=x;}
};

// notice how the friend function
// can access even the private members
// of the class
int geta(myclass ob)
{
return ob.a;
}

void main()
{
myclass obj;

obj.seta(100);

// accessed as usual
cout<<geta(obj);
}



Did you notice the specialty?


In the above example program the function geta() is just a general function
(friend of class, of course) but still it is able to access the private member
of the class (i.e. the variable ‘a’). The function is also called
as usual since it is not a member function.


This is because by declaring any non-member function as friend inside a class,
gives it access to the entire Private and Protected members of that class.


Many of you would be wondering what is gained by doing this all?


The answer is that there are circumstances when its use simplifies certain
operations, it is also widely used in overloading operators besides this there
are some other uses of friend functions none of which can be discussed here,
so we leave the use friend functions for future articles!


Related Articles:


Static Member Functions of Class

Much like the Static
Members
, there also exist static member functions. Just as static members,
static functions can also be accessed independently of any specific object and
thus its primary use is to pre-initialize static members before creation of
any object.


The following program illustrates how static member functions are declared
and used:



// Static Member Functions
#include <iostream.h>

class myclass
{
// declare a
static int a;

public:
// static function
static void init(int x){a=x;}

int get(){return a;}
};

// define a
int myclass::a;

void main()
{
// static functions may
// be called independently
// using the class name
myclass::init(100);

myclass obj;

cout<<obj.get();
}


In the above example the static members function (init() ) is used to initialize
the static member variable ‘a’ before object creation.


A few points to remember:




  • Static member functions can only access other static member of the class
    or global data.




  • Static member functions can’t have a non-static overloaded version.




  • They don’t have a ‘this’ pointer, this is because static
    functions can be called irrespective of specific object (using the class
    name and the scope resolution operator ‘::’).




With these restrictions they have very limited applications, one of them as
we discussed is to initialize other static members before object creation.


Related Articles:


Using Static Data Members in Classes

Let us start with a question.


Suppose we want to have some information (i.e. a variable) which should be
available ‘as is’ to all the objects of a particular class (ex.
the number of objects of that class available at a time). Then what would you
do? You can’t make it to be a regular member of the class because then,
every object would have its own copy of that information which should have been
common to all objects.


One way of achieving this is to declare that variable as global and access
it within the class wherever needed as a member. This is illustrated in the
program below; it keeps track of the number of objects present (defined) at
a particular time.



#include <iostream.h>

int obj_count=0;

class myclass
{
public:
myclass(){obj_count++;}
~myclass(){obj_count--;}

int count(){return obj_count;}
};

void main(void)
{
myclass o1;

cout<<o1.count();
cout<<endl;

myclass o2;

// here both these return
// the same information
cout<<o1.count();
cout<<endl;
cout<<o2.count();
cout<<endl;
}


But this is rather awkward, because how can we make a variable global which
would otherwise have been a part of the class itself!


So what do we do? We use static members!


Static member of a class are those whose only one copy exist among all the
objects of a class and is shared among all of them.


As I said, it is like having a global variable to store some information which
is needed by all the objects of a particular class.


This is illustrated in the program below which is the modified version of the
previous program to use static member variable.



// Using static member variables
#include <iostream.h>

class myclass
{
// static variable is
// declared
static int obj_count;
public:
myclass(){obj_count++;}
~myclass(){obj_count--;}

int count(){return obj_count;}
};

// IMPORTANT
// define the variable
int myclass::obj_count;

void main(void)
{
myclass o1;

cout<<o1.count();
cout<<endl;

myclass o2;

// here both these return
// the same information
cout<<o1.count();
cout<<endl;
cout<<o2.count();
cout<<endl;
}


Points to remember:




  • Static members of a class are declared by using the ‘static’
    keyword.




  • Only declaration is not enough, it must be defined somewhere outside the
    class.



  • All the static members are automatically initialized to 0 by the compiler.


Related Articles:


Using Virtual Base Classes to Avoid Ambiguity

Let’s start this with the following example program:



// this program contains errors
#include<iostream.h>

// base class
class base
{
public:
int a;
};

// derived class (1)
class derived1:public base
{
public:
int b;
};

// derived class (2)
class derived2:public base
{
public:
int c;
};

// derived class (3)
class derived3:public derived1, public derived2
{
public:
int d;
};

// main
void main()
{
derived3 ob;

// this is ambiguous
// since two copies of
// base is present in
// the class derived3
// one from derived1 &
// the other from derived2
ob.a=10;
}


The program above contains an error (as stated) in the following line:


ob.a=10;


Since the base class is inherited by the two classes (derived1 and derived2),
which are again inherited (both together) by another class derived3, there are
two copies of the base class (and hence two copies of variable ‘a’
too).


Therefore when we refer to the variable ‘a’ with respect to the
derived3 class then as there are two copies of it, it becomes ambiguous or confusing
for the compiler to select one from the two and hence it is reported as an ERROR.


This is very common error which creeps in when you write long and complex program
consisting of classes some of which are hierarchically inherited.


So how can we prevent this from happening?


Actually, we can prevent this by using the scope resolution operator but this
is not a permanent solution besides having other flaws. Then what else can we
do?


Yeah, you guessed it right; Virtual Base Class is he answer.


Now, have a look at the same program with slight modification (as to apply
the virtual base class method), now it’s perfectly all right!



// Virtual base classes
#include<iostream.h>

// base class
class base
{
public:
int a;
};

// derived class (1)
// notice the use of virtual keyword
class derived1:virtual public base
{
public:
int b;
};

// derived class (2)
// notice the use of virtual keyword
class derived2:virtual public base
{
public:
int c;
};

// derived class (3)
class derived3:public derived1, public derived2
{
public:
int d;
};

// main
void main()
{
derived3 ob;

// now it's O. K.
ob.a=10;
}


As you can see, we’re using virtual keyword to derive the classes (derived1
and derived2) from the base class.


This prevents other inheriting classes (which inherits more than one such derived
classes) to have only one copy of the base class and hence ruling out chances
of ambiguity.


Please note that the derived classes (derived1 and derived2 individually) still
contains one-one copy of base class, it is only when they are inherited is the
virtual nature comes into action.


We conclude this article with the following example program to illustrate all
that we have discussed so far in this article.



// Virtual base classes
#include<iostream.h>

// base class
class base
{
public:
int a;
};

// derived class (1)
// notice the use of virtual keyword
class derived1:virtual public base
{
public:
int b;
};

// derived class (2)
// notice the use of virtual keyword
class derived2:virtual public base
{
public:
int c;
};

// derived class (3)
class derived3:public derived1, public derived2
{
public:
int d;
};

// main
void main()
{
derived1 ob1;
derived2 ob2;
derived3 ob3;

// derived classes still
// contain one-one copy
// of the base class
ob1.a=10;
ob2.a=20;

// but the class derived
// form the classes of
// the above two objects
// contains only one copy
// of the base class
ob3.a=100;
}


Related Articles:


Parameterized Constructors of Derived Classes

In the previous article Constructors
and Destructors of Derived Classes
, we’re discussing about the
calling conventions of Constructors and Destructor functions of derived classes
whose base class also had them. There was one thing special about those constructors;
none of them were taking arguments.


If only the derived’s constructor takes parameters then also its O. K.
but what if both the base and derived class contains parameterized constructors
(as is obvious from the code below).



// this code contains ERRORS

// base class
class base
{
int a;

public:
base(int n)
{
//...
}
};

// derived class
class derived:public base
{
int b;

public:
derived(int m)
{
//...
}
};

//main
void main()
{
base b(10); //ok

derived d(10); // ERROR!!
// base's constructor
// will also be called and
// it needs parameters too !!
}



How’d you pass arguments to the base class constructor?


To answer this, we need to introduce Expanded from of Constructor Declaration
(of the derived class).



derived-constructor (arg): base1 (arg),
base2 (arg),
...
baseN (arg)
{
...
...
}


Here base1, base2 etc. are constructor functions of base classes, which the
derived class inherits.


Let’s have a look at an example program to understand this declaration:



// this code is ok

// base class
class base
{
int a;

public:
base(int n){a=n;}
};

// derived class
class derived:public base
{
int b;

public:
// since this class is derived
// from only one class 'base'
// therefore only one constructor
// is listed
derived(int m1,int m2):base(m2)
{b=m1;}
};

// main
void main()
{
base b(10); //ok

derived d(10,100); //ok
}




One thing to note here is, the argument which is to be passed to the base’s
constructor should be declared and accepted from the derived class constructor,
as in the line


derived(int m1,int m2):base(m2)
{b=m1;}


Here derived’s constructor is only using the parameter m1 but is accepting
another parameter m2 which is to be passed along to the constructor of the base
class.


Let us have a look at another example program which will clear all the confusions.
Keep reading the comments!



#include<iostream.h>

// base class (1)
class base1
{
protected:
int a;

public:
base1(int p1){a=p1;}
};

//base class (2)

class base2
{
protected:
int b;

public:
base2(int p2){b=p2;}
};

// derived class (1)

class derived1:public base1
{
protected:
int c;

public:
derived1(int p3,int p4):base1(p4)
{c=p3;}

void show(){cout<<a<<"\n"<<c;}
};

//derived class (2)

class derived2:public base1, public base2
{
public:
// this class inherits two base classes

// therefore we are using two base
// class constructors in the declaration
derived2(int p5,int p6):base1(p5),
base2(p6)
{
// empty


// used only to call the base's
// constructors with the passed
// arguments

// derived class constructor may not
// use any arguments passed to it
}

void show(){cout<<a<<"\n"<<b;;}
};

// main

void main()
{
derived1 d1(10,20);
derived2 d2(100,200);

d1.show();
cout<<endl;
d2.show();
}



Related Articles:


Check out this stream