what exactly is dynamic casting in c++ [duplicate] - c++

This question already has answers here:
Regular cast vs. static_cast vs. dynamic_cast [duplicate]
(8 answers)
Closed 9 years ago.
can anyone tell what exactly is dynamic casting means in c++.
where exactly can we use this dynamic casting?
this was asked to me in the interview and i went blank for this question:).

dynamic_cast is casting method to find out the object's class at runtime.
class Base
{
public:
virtual bool func1();
};
class Derived1 : Base
{
public:
virtual bool func1();
virtual bool funcDer1();
};
class Derived2 : Base
{
public:
virtual bool func1();
virtual bool funcDer2();
};
Base* pDer1 = new Derived1;
Base* pDer2 = new Derived2;
Derived2* pDerCasted = dynamic_cast<Derived2*>(pDer2);
if(pDerCasted)
{
pDerCasted->funcDer2();
}
-> We cannot call funcDer2 with pDer2 as it points to Base class
-> dynamic_cast converts the object to Derived2 footprint
-> in case it fails to do so, it returns NULL .( throws bad_cast in case of reference)
Note: Usually, Dynamic_cast should be avoided with careful OO design.

Try to use the search first
old answer

Dynamic casting is safely discovering the type of an object instance at runtime.
This is achieved by the compiler generating reference tables, which can be potentially rather large. For this reason, it is often disabled during compilation if the programmer knows that they do not use the feature.

Related

Does dynamic_cast work even when there is no inheritance? [duplicate]

This question already has answers here:
what is side-cast or cross-cast in Dynamic_cast in C++
(2 answers)
Closed 2 years ago.
std::bad_cast: https://en.cppreference.com/w/cpp/types/bad_cast
An exception of this type is thrown when a dynamic_cast to a reference type fails the run-time check (e.g. because the types are not related by inheritance)
So, if the types are not related by inheritance then it throws an error, so how it the following quote hold true?
https://stackoverflow.com/a/332086/462608
You can use it for more than just casting downwards – you can cast sideways or even up another chain.
What does this quote mean? Please give examples.
Sideways cast would be for example like this:
class Base1 { virtual ~Base1() = default; };
class Base2 { virtual ~Base2() = default; };
class Derived: public Base1, public Base2 {};
int main() {
Base1* p1 = new Derived;
Base2* p2 = dynamic_cast<Base2*>(p1);
}
Types Base1 and Base2 are unrelated to each other, but you can cast between the pointers because Derived inherits from both.
I'm not sure what did the original answerer mean by "cast [...] up another chain", but I guess they meant a situation where you would have a Base1* pointer and would cast to Base2 parent.

How delete knows, where the object starts in the memory? [duplicate]

This question already has answers here:
Is the whole object freed with a non-virtual destructor and a Base class pointer?
(6 answers)
Closed 3 years ago.
Consider following code:
class Base1 { public: int a1; };
class Base2 { public: int a2; };
class Foo: public Base1, public Base2 {}
int main() {
Foo *foo = new Foo();
Base2 *b = foo;
delete b; // note pointer foo != pointer b
}
How delete knows, where the memory, which should be freed, begins?
Since all the classes contain only atomic integers, is virtual destructor needed in this particular case?
is virtual destructor needed in this particular case?
Yes. Deleting an object through a pointer to a base with non-virtual destructor has undefined behaviour.
How delete knows, where the object starts in the memory?
In case of non-virtual destructor, you pass the starting address to the operator (or if you don't, then you have UB), so there's no mystery.
In case of virtual destructor, virtual dispatch is used. The compiler will somehow implement it to work correctly. Typically, a "vptr" is used.

How does vtable handle multiple inheritance? [duplicate]

This question already has answers here:
Object layout in case of virtual functions and multiple inheritance
(4 answers)
Closed 4 years ago.
I understand that for single inheritance a pointer to a virtual function table is added to determine what parent class functions to call at runtime.
class Genius {
int IQ;
public:
virtual void brag();
};
class Me : public Genius {
int age;
};
When instantiated, the memory layout of Me should look something like
pointer to Genius vtable
int iq
int age
But what happens in the case of multiple inheritance?
// Assume CoolDude has virtual functions as well
class Me : public Genius, public CoolDude {
int age;
};
What does the memory layout of the Me class look like now? How is multiple inheritance handled?
The class will have 2 pointers to vtables, one to its implementation of Genius and one to its implementation of CoolDude. When casting to a base class, the the returned pointer will differ from the original by the offset of the vtable(and other members) or the base class.

C++ dynamic_cast returning NULL although object is of a derived type [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a strange problem, where a dynamic_cast is returning a NULL pointer although the object given in the expression is of a derived type with an inheritance path to the type of the cast.
Unfortunately, i cannot post original code, so here is the situation roughly reconstructed:
I have a clas hierarchy of the following type:
class A
class B
class C : public A, B
class D : public C
All classes have virtual members.
Now assume I have an object of concrete type D.
In a function where this object is passed in as a B*, i have a cast of this type:
C* func(B* pObject)
{
return dynamic_cast<C*>(pObject);
}
The cast returns NULL although the object seems well defined.
VC++ reports it as being a D when looking at the object in debugger when hovering over pObject. (might this be misleading?)
Is this cast supposed to work?
Imo this cast should be allowed. Am i missing something?
What can i do to analyse this issue?
Could there be an issue with the multiple inheritance?
This is on Visual C++ 2013 Pro if it makes any difference.
Your problem is elsewhere.
Consider
#include <iostream>
struct A {};
struct B {virtual ~B() = default;};
struct C : A, B {};
struct D : C {};
int main()
{
D d;
D* pd = &d;
B* pb = dynamic_cast<B*>(pd);
C* pc = dynamic_cast<C*>(pb);
std::cout << pc; // this is not nullptr
}
This proves that C* is reachable from B* for an pointer to an object of type D, when only B (the source type in the second cast) is explicitly polymorphic.
See https://ideone.com/ifxYgV

Different return value of an overridden class [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
c++ virtual function return type
I have a simple but confusing question here. Is it legal to have a different return value type for overridden methods than the abstact ones defined in the base class?? I did that and the compiler didn't complain... could someone please explain?
class MyBaseClass
{
int value;
public:
virtual int getValue() = 0;
};
class MyClass : public MyBaseClass
{
double value;
public:
virtual double getValue(); // here!!! return is double, not int
};
double MyClass::getValue()
{
return this->value;
}
The compiler totally accepted something similar (MSVC und MinGW)... could anyone please exaplain to what extent this is legal?
The return type is allowed to differ but only in a bery restrictive way and you code is illegal. The only way the return type of an override is allowed to differ is that can be covariant if yhe return type of the base is a pointer or a reference. Put differently: if the base returns a pointer or a reference to a base class the overrude is allowed to return a pointer or a reference, respectively, to a class derived of the base.
Are you overriding ? it looks like you have written a method and nothing else.