std::unique_ptr with derived class

If they are polymorphic types and you only need a pointer to the derived type use dynamic_cast: Derived *derivedPointer = dynamic_cast<Derived*>(basePointer.get()); If they are not polymorphic types only need a pointer to the derived type use static_cast and hope for the best: Derived *derivedPointer = static_cast<Derived*>(basePointer.get()); If you need to convert a unique_ptr containing a … Read more

Pointer to array of unspecified size “(*p)[]” illegal in C++ but legal in C

Dan Saks wrote about this in 1995, during the lead up to C++ standardisation: The committees decided that functions such as this, that accept a pointer or reference to an array with unknown bound, complicate declaration matching and overload resolution rules in C++. The committees agreed that, since such functions have little utility and are … Read more

Displaying the address of a string

If you use &hello it prints the address of the pointer, not the address of the string. Cast the pointer to a void* to use the correct overload of operator<<. std::cout << “String address = ” << static_cast<void*>(hello) << std::endl;

Dereference void pointer

It doesn’t make sense to dereference a void pointer. How will the compiler interpret the memory that the pointer is pointing to? You need to cast the pointer to a proper type first: int x = *(int*)lVptr;

Declaring type of pointers?

Type-safety. If you don’t know what p is supposed to point to, then there’d be nothing to prevent category errors like *p = “Nonsense”; int i = *p; Static type checking is a very powerful tool for preventing all kinds of errors like that. C and C++ also support pointer arithmetic, which only works if … Read more

Dereferencing type-punned pointer will break strict-aliasing rules

The problem occurs because you access a char-array through a double*: char data[8]; … return *(double*)data; But gcc assumes that your program will never access variables though pointers of different type. This assumption is called strict-aliasing and allows the compiler to make some optimizations: If the compiler knows that your *(double*) can in no way … Read more

C++ Access derived class member from base class pointer

No, you cannot access derived_int because derived_int is part of Derived, while basepointer is a pointer to Base. You can do it the other way round though: Derived* derivedpointer = new Derived; derivedpointer->base_int; // You can access this just fine Derived classes inherit the members of the base class, not the other way around. However, … Read more