#include <iostream>
#include <memory>
class Base
{
public:
virtual void foo() = 0;
};
class Derived : public Base
{
public:
void foo() override { std::cout << "Derived" << std::endl; }
};
class Concrete
{
public:
void Bar() { std::cout << "concrete" << std::endl; }
};
int main()
{
std::unique_ptr<Concrete> ConcretePtr = nullptr;
ConcretePtr->Bar();
std::unique_ptr<Base> BasePtr;
BasePtr->foo();
return 0;
}
I assume declaring a unique_ptr to a concrete type Concrete
, allocates memory for an object of type Concrete
and the unique_ptr starts pointing to it. Is my assumption/understanding correct ? I ask because ConcretePtr->Bar();
prints "concrete" to the console. But, if I make a unique pointer to an interface Base
, it does not know the exact type of object that I need and does not allocate/acquire resources in the memory.
This fails at BasePtr->foo();
with BasePtr._Mypair._Myval2 was nullptr.
Why does the first declaration std::unique_ptr<Concrete> ConcretePtr = nullptr;
allocate an object by itself ? what if I did not want it to be pointing to some real object at that very line of code, but wanted only a smart pointer ?
Now if I change the declaration to be std::unique_ptr<Concrete> ConcretePtr;
and the Concrete
type to be the following,
class Concrete
{
int ConcreteNum;
public:
void Bar()
{
std::cout << "concrete" << std::endl;
ConcreteNum = 38;
std::cout << ConcreteNum << std::endl;
}
};
it fails at ConcreteNum = 38;
complaining that this
was nullptr
; if this this
was nullptr
then why and how did the earlier call (where Concrete
did not have any state ConcreteNum
) to Bar
work ?
Moreover why does it not fail at ConcretePtr->Bar();
(this ->
requires a concrete object, does it not ? what was this
here ?) but inside Bar
, in that assignment ?
I see the same issue with std::shared_ptr
as well. I'm not very sure of the difference between declaration, initialization & assignment. Please help me understand.
I'm using MSVC.