×

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

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 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.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

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...

3 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 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.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute 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.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.