0

I just want to test an inheritance pattern but it seems I lacks some understanding. I thought father class's constructor should be evoked. Some direction is apprecitated

#include <stdio.h>
#include <iostream>
#include <memory>


template<class Gender, class Race, class ChildType>
class Father 
{
public:
    Father() {
       std::cout << "var = " << ChildType::var   << std::endl;
    };
};


class Male {
public:

};

class Vietnam {
public:


};

class Worker {
public:

};


class Child : public Father<Male, Vietnam, Child>
{
  public:
    static int var;
};

int Child::var(10);


int main() {

  std::shared_ptr<Father<Male, Vietnam, Child>> child(Child());

return 1;
}
TSL_
  • 1,879
  • 3
  • 32
  • 53
  • 4
    Most vexing parse. – jxh Aug 06 '20 at 09:43
  • 1
    Anyway, it's not clear what you expect `child(Child())` to do, even if it did what you think... `shared_ptr` needs a dynamically allocated instance, not a value, and you should use `std::make_shared()` to get that. – underscore_d Aug 06 '20 at 09:45
  • I think I am getting to the point too. Shared_ptr requires an instance initialization somewhere – TSL_ Aug 06 '20 at 09:47
  • so... Child() alone is not an instantiation? I've just tried new Child() and it does initialize an instance. Thank you for the answer by the way – TSL_ Aug 06 '20 at 13:01
  • @TSL_: a `shared_ptr` takes a pointer for initialization. `make_shared` creates a `shared_ptr` instance initialized with a pointer to a dynamically allocated object. – jxh Aug 06 '20 at 14:27
  • @TSL_: [Difference in make_shared and normal shared_ptr in C++](https://stackoverflow.com/q/20895648/315052) – jxh Aug 06 '20 at 14:36
  • @jxh: thank you for pointing it out such a comprehensive post. I'll have to read it slowly – TSL_ Aug 07 '20 at 03:10

1 Answers1

0

This code declares a function called child returning a shared_ptr which is not what you hoped for:

std::shared_ptr<Father<Male, Vietnam, Child>> child(Child());

You may fix it with this:

auto p = make_shared <Father<Male, Vietnam, Child>>();
artm
  • 16,141
  • 4
  • 27
  • 46