Open In App

Object Slicing in C++

Last Updated : 22 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When a derived class object is assigned to a base class object in C++, the derived class object’s extra attributes are sliced off (not considered) to generate the base class object; and this whole process is termed object slicing. In simple words, when extra components of a derived class are sliced or not used and the priority is given to the base class’s object this is termed object slicing. 

In C++, a derived class object can be assigned to a base class object, but the other way is not possible. To tackle this slicing problem we can use a dynamic pointer.

Moreover, Object slicing happens when a derived class object is assigned to a base class object, and additional attributes of a derived class object are sliced off to form the base class object.

 

C++




// C++ program to demonstrate what is object slicing
class Base {
    int x, y;
};
 
class Derived : public Base {
    int z, w;
};
 
int main()
{
    Derived d;
 
    // Object Slicing,
    // z and w of d are sliced off
    Base b = d;
}


Object Slicing image

Object Slicing


C++




// C++ program to demonstrate the mechanism or working of
// of the object slicing technique
#include <iostream>
using namespace std;
 
// Base class
class Base {
protected:
    int i;
 
public:
    Base(int a) { i = a; }
    virtual void
    display() // virtual function which is declared in base
              // class and re-declared in derived class
    {
        cout << "I am Base class object, i = " << i << endl;
    }
};
 
// Derived class
class Derived : public Base {
    int j;
 
public:
    Derived(int a, int b)
        : Base(a)
    {
 
        // assigning the value to the data members of
        // derived class
        j = b;
    }
    virtual void display()
    {
        cout << "I am Derived class object, i = " << i
             << ", j = " << j << endl;
    }
};
 
// Global method, Base class
// object is passed by value
void somefunc(Base obj) { obj.display(); }
 
int main()
{
    Base b(33);
    Derived d(45, 54);
    somefunc(b);
 
    // Object Slicing, the member j of d is
    // sliced off
    somefunc(d);
    return 0;
}


Output: 

I am Base class object, i = 33
I am Base class object, i = 45

We can avoid the above-unexpected behavior with the use of pointers or references. Object slicing doesn’t occur when pointers or references to objects are passed as function arguments since a pointer or reference of any type takes the same amount of memory. For example, if we change the global method myfunc() in the above program to the following, object slicing doesn’t happen. 

C++




// REFERENCE TO ABOVE
 
// rest of code is similar to above
void somefunc (Base &obj)
{
    obj.display();
}          
// rest of code is similar to above


Output: 

I am Base class object, i = 33
I am Derived class object, i = 45, j = 54

We get the same output if we use pointers.

One of the application of object slicing is seen when an object of derived class is passed to a function which takes object of base class as an argument. This has been demonstrated below.

Example:

C++




// rest of code is similar to above
void somefunc (Base *objp)
{
    objp->display();
}
 
int main()
{
    Base *bp = new Base(33) ;
    Derived *dp = new Derived(45, 54);
    somefunc(bp);
    somefunc(dp);  // No Object Slicing
    return 0;
}


Output: 

I am Base class object, i = 33
I am Derived class object, i = 45, j = 54

Object slicing can be prevented by making the base class function pure virtual thereby disallowing object creation. It is not possible to create the object of a class that contains a pure virtual method.



Similar Reads

Exception Handling and Object Destruction in C++
An exception is termed as an unwanted error that arises during the runtime of the program. The practice of separating the anomaly-causing program/code from the rest of the program/code is known as Exception Handling. An object is termed as an instance of the class which has the same name as that of the class. A destructor is a member function of a
4 min read
C++ | Class and Object | Question 3
What is the difference between struct and class in C++? (A) All members of a structure are public and structures don't have constructors and destructors (B) Members of a class are private by default and members of struct are public by default. When deriving a struct from a class/struct, default access-specifier for a base class/struct is public and
1 min read
C++ | Class and Object | Question 2
Predict the output of following C++ program #include<iostream> using namespace std; class Empty {}; int main() { cout << sizeof(Empty); return 0; } (A) A non-zero value (B) 0 (C) Compiler Error (D) Runtime Error Answer: (A) Explanation: See Why is the size of an empty class not zero in C++Quiz of this Question
1 min read
C++ | Class and Object | Question 3
class Test { int x; }; int main() { Test t; cout << t.x; return 0; } (A) 0 (B) Garbage Value (C) Compiler Error Answer: (C) Explanation: In C++, the default access is private. Since x is a private member of Test, it is compiler error to access it outside the class.Quiz of this Question
1 min read
C++ | Class and Object | Question 4
Which of the following is true? (A) All objects of a class share all data members of class (B) Objects of a class do not share non-static members. Every object has its own copy. (C) Objects of a class do not share codes of non-static methods, they have their own copy (D) None of the above Answer: (B) Explanation: Every object maintains a copy of no
1 min read
C++ | Class and Object | Question 5
Assume that an integer and a pointer each takes 4 bytes. Also, assume that there is no alignment in objects. Predict the output following program. #include<iostream> using namespace std; class Test { static int x; int *ptr; int y; }; int main() { Test t; cout << sizeof(t) << " "; cout << sizeof(Test *); } (A) 12 4
1 min read
C++ | Class and Object | Question 6
Which of the following is true about the following program #include <iostream> class Test { public: int i; void get(); }; void Test::get() { std::cout << "Enter the value of i: "; std::cin >> i; } Test t; // Global object int main() { Test t; // local object t.get(); std::cout << "value of i in local t: "
1 min read
Where is an object stored if it is created inside a block in C++?
There are two parts of memory in which an object can be stored: stack - Memory from the stack is used by all the members which are declared inside blocks/functions. Note that the main is also a function.heap - This memory is unused and can be used to dynamically allocate the memory at runtime. The scope of the object created inside a block or a fun
3 min read
cerr - Standard Error Stream Object in C++
Standard output stream(cout): cout is the instance of the ostream class. cout is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream(cout) using the insertion operator(<<). Standard error stream (cerr): cerr is the sta
2 min read
Brief Overview & Comparison of Object-Oriented Programming from C to Java
In this article, you will get the ability to think how really OOP works in Java through C. Through C, you will understand the concept of Polymorphism, Inheritance, Encapsulation, Class, Objects, etc. As you also know C language don't support OOP, but we can understand the concept behind it by defining a fine structure as a Class and Creating its Id
3 min read
How to Manipulate cout Object using C++ IOS Library?
C++ ios_base class has its aspects to format cout object to display different formatting features. For example, the following ios_base class can format cout object to display trailing decimal points, add + before positive numbers, and several other formatting features using class scope static constants. Class Scope Static Constants: Class scope sta
5 min read
Different ways to instantiate an object in C++ with Examples
prerequisite: C++ Classes and Objects Different Ways to Instantiate an Object In C++, there are different ways to instantiate an objects and one of the method is using Constructors. These are special class members which are called by the compiler every time an object of that class is instantiated. There are three different ways of instantiating an
6 min read
Object Composition-Delegation in C++ with Examples
Object Compositions An object is a basic unit of Object-Oriented Programming and represents real-life entities. Complex objects are objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. This process of building complex objects from simp
5 min read
Printing the Address of an Object of Class in C++
Prerequisite: Classes and Objects in C++ The location of an object in the memory is called its address. Addressing is a necessary part of C++, it enables us to use any element as a reference and maintains the uniqueness of all the elements whether it is any variable, object, or container. In this article, we will see how to access the address of an
3 min read
How to Get a Unique Identifier For Object in C++?
Prerequisite: Classes and Objects in C++ A single entity within a given system is identified by a string of numbers or letters called a unique identifier (UID). UIDs enable addressing of that entity, allowing access to and interaction with it. There are a few choices, depending on your "uniqueness" requirements: Pointers are acceptable if unique in
3 min read
Difference Between Object And Class
Class is a detailed description, the definition, and the template of what an object will be. But it is not the object itself. Also, what we call, a class is the building block that leads to Object-Oriented Programming. It is a user-defined data type, that holds its own data members and member functions, which can be accessed and used by creating an
6 min read
Can a C++ class have an object of self type?
A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type. For example, following program works fine. // A class can have a static member of self type #include<iostream> using namespace std; class Test { static Test self; // works fine /* other stuff
2 min read
Preventing Object Copy in C++ (3 Different Ways)
Many times, user wants that an instance of a C++ class should not be copied at all. So, the question is how do we achieve this ? There are three ways to achieve this : Keeping the Copy Constructor and Copy assignment operator as private in the class. Below is the C++ implementation to illustrate how this can be done. #include <iostream> using
3 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
9 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data types in C can be classified as follows: Types Description Data Types
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
Article Tags :
Practice Tags :