Pointer up

I have the following contrived example (coming from real code):

template <class T>
class Base {
public:
 Base(int a):x(a) {}
    Base(Base<T> * &other) { }
    virtual ~Base() {}
private:
 int x;
};

template <class T>
class Derived:public Base<T>{
public:
  Derived(int x):Base<T>(x) {}
  Derived(Derived<T>* &other): Base<T>(other) {}

};


int main() {
 Derived<int> *x=new Derived<int>(1);
 Derived<int> y(x);
}

When I try to compile this, I get:

1X.cc: In constructor β€˜Derived<T>::Derived(Derived<T>*&) [with T = int]’:
1X.cc:27:   instantiated from here
1X.cc:20: error: invalid conversion from β€˜Derived<int>*’ to β€˜int’
1X.cc:20: error:   initializing argument 1 of β€˜Base<T>::Base(int) [with T = int]’

1) Obviously, gcc is confused by the constructors. If I remove the link from the constructors, then the code compiles. Therefore, I suppose something went wrong with links to link pointers. Can someone tell me what is going on here?

2) A little unrelated question. If I did something terrible, like "delete another" in the constructor (bear with me), what happens when someone passes me a pointer to something on the stack?

E.g. Derived<int> x(2);
     Derived<int> y(x);

where 

 Derived(Derived<T>*& other) { delete other;}

How can I make sure the pointer is legitimately pointing to something on the heap?

+3
source share
5

Base<T> Derived<T>, Base<T>* Derived<T>*. , .

, , , , Base :

Base(Base<T> * &other) {
    Base<T> *thing = new Base<T>(12);
    other = thing;
}

, Derived<T>, Derived<T>. .

+10

:

struct Base {};
struct Derived : Base {};
struct Subclass : Base {};

int main() {
  Derived d;
  Derived* p = &d;
  Derived*& d_ptr = p;

  Base*& b_ptr = d_ptr; // this is not allowed, but let say it is

  Base b;
  b_ptr = &b; // oops! d_ptr no longer points to a Derived!

  Subclass s;
  b_ptr = &s; // oops! d_ptr no longer points to a Derived!
}

"" ctor, , b_ptr = d_ptr .

+3

, - , , . , , , , - , .

, , , , , , .

+2

x , , new Derived<int>.

, . , - (, ++ ). , , , , .

0

, .

Base(Base<T> * other) { }

Derived(Derived<T>* other): Base<T>(other) {}

.

And, like others, I don’t think you can legitimately find out if a pointer points to a bunch.

Edit : why you can't do what you are trying to: consider an example:

Derived1<int> *x = new Derived1<int>
Base<int> **xx =&x;
Derived2<int> y;
*xx = &y;

Where are Derived1 and Derived2 different classes derived from Base? Do you think this is legal? Now, when does x of type Derived1 * point to Derived2?

0
source

Source: https://habr.com/ru/post/1726380/


All Articles