Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance - why is this illegal?

I'm going through a C++ quiz. And came across the following code - it's illegal, but I can't understand why. Can anyone explain why this line:

Box* b1 = s1->duplicate();

generates the compiler error, "cannot convert from Shape* to Box"? I assumed that s1->duplicate() is calling Box::duplicate() because s1 actually points to a Box - but from the compiler error it looks like it's calling Shape::duplicate().

#include <iostream>

struct Shape
{
  virtual Shape* duplicate()
  {
    return new Shape;
  }

  virtual ~Shape() {}
};

struct Box : public Shape
{
  virtual Box* duplicate()
  {
    return new Box;
  }

};

int main(int argc, char** argv) 
{ 
  Shape* s1 = new Box;

  Box* b1 = s1->duplicate();

  delete s1;
  delete b1;
  return 0; 
}
like image 336
BeeBand Avatar asked Aug 15 '12 21:08

BeeBand


People also ask

What is inheritance theft?

Inheritance hijacking can be simply defined as inheritance theft — when a person steals what was intended to be left to another party. This phenomenon can manifest in a variety of ways, including the following: Someone exerts undue influence over a person and convinces them to name them an heir.

Why do people refuse inheritance?

Key Takeaways. Common reasons for disclaiming an inheritance include not wishing to pay taxes on the assets or ensuring that the inheritance goes to another beneficiary—for example, a grandchild. Specific IRS requirements must be followed in order for a disclaimer to be qualified under federal law.

What is a inheritance in legal terms?

Inheritance refers to property acquired through the laws of descent and distribution. Though sometimes used in reference to property acquired through a will, the legal meaning of inheritance includes only property that descends to an heir through intestacy, when a person has died intestate.

What is inheritance law in USA?

Inheritance laws are statutes and regulations that determine how individuals receive assets from the estate of a deceased family member. These laws ensure that beneficiaries can acquire some form of inheritance in the event that a will was never written or doesn't cover all of the deceased person's assets.


1 Answers

C++ language is statically typed. The decisions about the legality of your call are made at compile time. The compiler, obviously, cannot know that s1->duplicate() returns a pointer to a Box object. Under these circumstances, it would be illogical to expect it to accept your code.

Yes, s1->duplicate() indeed calls Box::duplicate in your example, but how do you expect the compiler to know this? One can say that it is "obvious" from your specific example, but the specification of this language feature makes no exception for such "obvious" cases.

like image 89
AnT Avatar answered Oct 13 '22 13:10

AnT