Someone mentioned it in the IRC as the slicing problem.
C++ – object slicing
cc++-faqinheritanceobject-slicing
Related Solutions
A pointer can be re-assigned:
int x = 5; int y = 6; int *p; p = &x; p = &y; *p = 10; assert(x == 5); assert(y == 10);
A reference cannot be re-bound, and must be bound at initialization:
int x = 5; int y = 6; int &q; // error int &r = x;
A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary
&
operator and a certain amount of space that can be measured with thesizeof
operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.int x = 0; int &r = x; int *p = &x; int *p2 = &r; assert(p == p2); // &x == &r assert(&p != &p2);
You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection.
int x = 0; int y = 0; int *p = &x; int *q = &y; int **pp = &p; **pp = 2; pp = &q; // *pp is now q **pp = 4; assert(y == 4); assert(x == 2);
A pointer can be assigned
nullptr
, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference tonullptr
, but this is undefined and will not behave consistently./* the code below is undefined; your compiler may optimise it * differently, emit warnings, or outright refuse to compile it */ int &r = *static_cast<int *>(nullptr); // prints "null" under GCC 10 std::cout << (&r != nullptr ? "not null" : "null") << std::endl; bool f(int &r) { return &r != nullptr; } // prints "not null" under GCC 10 std::cout << (f(*static_cast<int *>(nullptr)) ? "not null" : "null") << std::endl;
You can, however, have a reference to a pointer whose value is
nullptr
.Pointers can iterate over an array; you can use
++
to go to the next item that a pointer is pointing to, and+ 4
to go to the 5th element. This is no matter what size the object is that the pointer points to.A pointer needs to be dereferenced with
*
to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses->
to access its members whereas a reference uses a.
.References cannot be put into an array, whereas pointers can be (Mentioned by user @litb)
Const references can be bound to temporaries. Pointers cannot (not without some indirection):
const int &x = int(12); // legal C++ int *y = &int(12); // illegal to take the address of a temporary.
This makes
const &
more convenient to use in argument lists and so forth.
The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.
Here's an example class with a constructor that can be used for implicit conversions:
class Foo
{
public:
// single parameter constructor, can be used as an implicit conversion
Foo (int foo) : m_foo (foo)
{
}
int GetFoo () { return m_foo; }
private:
int m_foo;
};
Here's a simple function that takes a Foo
object:
void DoBar (Foo foo)
{
int i = foo.GetFoo ();
}
and here's where the DoBar
function is called:
int main ()
{
DoBar (42);
}
The argument is not a Foo
object, but an int
. However, there exists a constructor for Foo
that takes an int
so this constructor can be used to convert the parameter to the correct type.
The compiler is allowed to do this once for each parameter.
Prefixing the explicit
keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar (42)
. It is now necessary to call for conversion explicitly with DoBar (Foo (42))
The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:
- You have a
MyString
class with a constructor that constructs a string of the given size. You have a functionprint(const MyString&)
(as well as an overloadprint (char *string)
), and you callprint(3)
(when you actually intended to callprint("3")
). You expect it to print "3", but it prints an empty string of length 3 instead.
Related Topic
- C++ – When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used
- C++ – The Definitive C++ Book Guide and List
- C++ – the “–>” operator in C/C++
- C++ – move semantics
- C++ – the copy-and-swap idiom
- C++ – The Rule of Three
- C++ – What are the basic rules and idioms for operator overloading
- Java – Why is processing a sorted array faster than processing an unsorted array
Best Answer
"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.
For example,
So an object of type
B
has two data members,foo
andbar
.Then if you were to write this:
Then the information in
b
about memberbar
is lost ina
.