Loading....
Coupon Accepted Successfully!

 

Object Slicing

Virtual functions permit us to manipulate both base and derived objects using similar member functions with no modifications. Virtual functions can be invoked using a pointer or reference. If we do so, object slicing takes place. The following program takes you to the real thing:
 

15.13 Write a program to declare reference to object and invoke functions.

#include<constream.h>

#include<iostream.h>

class B

{

int j;

public:

B (int jj) {j=jj;}

virtual void joy()

{

cout<<“\n In class B”;

cout<<endl<<“ j=”<<j;

}

};

class D : public B

{

int k;

public:

D (int jj, int kk) : B (jj)
{k=kk;}
void joy()
{
B::joy();
cout<<“\n In class D”;
cout<<endl<<“ k=”<<k;
}

};
void main()
{

clrscr();
B b(3);
D d (4,5);
B &r=d;
cout<<“\n Using Object”;
d.joy();
cout<<“\n Using Reference”;
r.joy();

}

OUTPUT
Using Object
In class B
j= 4
In class D
k= 5
Using Reference
In class B
j= 4
In class D
k= 5

 

Explanation: In the above program, a reference object r is created to an object d using the statement B &r = d;. The member function joy() is invoked using r and d objects. The output is similar.
 

15.14 Write a program to demonstrate object slicing.

#include<iostream.h>

#include<constream.h>

class A

{

public:

int a;
A() {a=10;}

};
class B: public A
{

public:
int b;
B() {a=40; b=30;}

};
void main()
{

clrscr();
A x;
B y;
cout<<“ a=”<<x.a <<“”;
x=y;
cout<<“ Now a=”<<x.a;

}

OUTPUT
a=10 now a=40

Explanation:
In the above program, class A has only one data member a and derived class B has one member b. In function main(), objects x and y of classes A and B are declared. The object x has only one member, that is, a and the object y has two members a and b. The statement x = y, that is, the derived class object, is assigned to the base class object. In such an assignment, only base, class part of the derived object is assigned to the base class object. Thus, if an object of a derived class is assigned to a base class object, the compiler allows it. However, it copies only the base class members of the object, and this process is known as object slicing.




Test Your Skills Now!
Take a Quiz now
Reviewer Name