Posts

Showing posts with the label dynamic-cast

C++ downgrade parent pointer to child pointer used as function parameter

C++ downgrade parent pointer to child pointer used as function parameter I want use child pointer in place of parent parameter in some function. Here is simplified code #include <iostream> #include <string> using namespace std; class Parent { private: string value; public: void SetValue(const string& in){ value = in; } const string& GetValue() const { return value; } virtual ~Parent() {}; }; class Child : public Parent { }; void Func(Parent* obj) { Child* cobj = dynamic_cast<Child*>(obj); cobj->SetValue("new value"); delete cobj; } int main(int argc, char** argv) { Child* cobj = new Child(); Func(cobj); cout<<"value: "<<cobj->GetValue(); return 0; } But it returns value: Func does not set the value property. How can I fix the code? UPDATE1: But with this code: value: Func #include <iostream> #include <string> using namespace std; class Parent...