×

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes are removed (not considered). This entire process is known as object slicing. Object slicing is the process of giving the object of the base class priority over additional components of a derived class that are either sliced or not used.

In the C++ programming language, it is feasible to assign an object from a base class to an object from a derived class, but not the other way around. We can utilise a dynamic pointer to solve this slicing difficulty.

Object Slicing in C++

Example 1:

// The mechanism or operation of the object slicing 
// approach is illustrated in x C++ program.
#include <iostream>
using namespace std ;
// Based class
class Based {
protected :
	int j ;
public:
	Based ( int x ) { 
        j = x ;
    }
	virtual void
	display ( ) // virtual function that is initially declared in the base class 
			// and then re-declared in the derived class
	{
		cout<< "I am Base class object, j = " << j <<endl ;
	}
} ;
// Derived class
class Derived : public Based {
	int j ;
public:
	Derived(int x, int y)
		: Based(x)
	{
		// assigning the value to the data members of
		// derived class
		j = y ;
	}
	virtual void display()
	{
		cout<< "I am Derived class object, j = " << j
			<< ", j = " << j <<endl ;
	}
}  ;
// Global method, Base class
// object is passed by value
void somefunction( Basedobj ) { 
obj.display() ;
    }
int main()
{
	Based y(55) ;
	Derived d(34, 43) ;
	somefunction(y) ;
	// Object Slicing, the member j of d is
	// sliced off
	somefunction(d) ;
	return 0 ;
}

Output:

Object Slicing in C++

Using pointers or references, we can avoid the aforementioned unwanted behaviour. Object slicing is avoided when pointers or references to objects are provided as function arguments because each form of pointer or reference requires the same amount of memory. For instance, object slicing is prevented if the global function myfunction() in the program above is changed to the following.

Example 2:

// The mechanism or operation of the object slicing 
// approach is illustrated in x C++ program.
#include <iostream>
using namespace std ;
// Based class
class Based {
protected :
	int j ;
public:
	Based ( int x ) { 
	j = x ;
    }
	virtual void
	display ( ) // virtual function that is initially declared in the base class 
			// and then re-declared in the derived class
	{
		cout<< "I am Base class object, j = " << j <<endl ;
	}
} ;
// Derived class
class Derived : public Based {
	int j ;
public:
	Derived(int x, int y)
		: Based(x)
	{
		// assigning the value to the data members of
		// derived class
		j = y ;
	}
	virtual void display()
	{
		cout<< "I am Derived class object, j = " << j
			<< ", j = " << j <<endl ;
	}
}  ;
// rest of code is similar to the above code except this part
void somefunction( Based&obj )
{
	obj.display();
}		
// rest of code is similar to above code except this part
int main()
{
	Based y(55) ;
	Derived d(34, 43) ;
	somefunction(y) ;
	// Object Slicing, the member j of d is
	// sliced off
	somefunction(d) ;
	return 0 ;
}

Output:

Object Slicing in C++

If we use pointers, the result is the same.       

When an object of a derived class is supplied to a function that also accepts an object of a base class as an argument, object slicing is used.

Example 3:

// The mechanism or operation of the object slicing 
// approach is illustrated in x C++ program.
#include <iostream>
using namespace std ;
// Based class
class Based {
protected :
	int j ;
public:
	Based ( int x ) { 
	j = x ;
    }
	virtual void
	display ( ) // virtual function that is initially declared in the base class 
			// and then re-declared in the derived class
	{
		cout<< "I am Base class object, j = " << j <<endl ;
	}
} ;
// Derived class
class Derived : public Based {
	int j ;
public:
	Derived(int x, int y)
		: Based(x)
	{
		// assigning the value to the data members of
		// derived class
		j = y ;
	}
	virtual void display()
	{
		cout<< "I am Derived class object, j = " << j
			<< ", j = " << j <<endl ;
	}
}  ;
// rest of code is similar to the above code except this part
void somefunc (Based *objp)
{
	objp->display();
}
int main()
{
	Based *xp = new Based(99) ;
	Derived *yp = new Derived(89, 98);
	somefunc(xp);
	somefunc(yp); // No Object Slicing
	return 0;
}

Output:

Object Slicing in C++

By making the base class function pure virtual and forbidding object creation, object slicing can be avoided. A class that includes a pure virtual method cannot have its objects created.


Related Topics

C++ Infinite loop

The term "infinite loop" refers to a loop that does not terminate the loop according to the condition. In some cases, an infinite loop may be required in programming, or...

4 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

Print Table Using While Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.