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;
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With