Casting to base class validity - c++

Say I have a class named Base and a class that derives from it called SuperBase. Given that add takes in a Base*, would either of these be valid:
SuperBase *super = new SuperBase;
bases.add(super);
Or
SuperBase *super = new SuperBase;
bases.add((Base*)super);

The first works as long as SuperBase publicly derives from Base, via an implicit conversion from derived-to-base:
struct base { virtual ~base() {} };
struct derived : base {};
base* b = new derived; // okay
The second works as well, but ignores the protection of Base:
struct derived : private base {}; // private base
base* b = new derived; // not okay, base is private
base* b = (base*)(new derived); // okay, but gross
If it's private, you probably shouldn't cast to it.

Both are valid - a child can be used in a place where a reference/pointer to parent is expected. This is called polymorphism.

Both would be valid, though type-casting super to Base* is not necessary.

Related

Access protected members of an existing base object

Lets say I have a base class with protected member:
class Base
{
public:
Base(int data)
: m_attribute(data) {}
protected:
int m_attribute;
};
and derived class from base:
class Derived : public Base
{
public:
int get_attribute()
{
return m_attribute;
}
};
First of all: I can do this, right? Is this totally legal?
If yes, then here is the question:
I can't change anything in a Base class;
I have a Base class object, and I need to access its m_attribute member;
Should I do downcasting from this base class object to derived class object first, and then call get_attribute() function? Something like this:
Base base(5);
Derived* derived = static_cast < Derived*>(&base);
int base_attribute = derived->get_attribute();
Or what are other ways to access protected member? I know that friend function is an option, but I can't change anything in the base class
Should I do downcasting from this base class object to derived class object first, and then call get_attribute() function?
Most definitely not. An instance of a base class is not an instance of a derived class. Your conversion is ill-formed.
Here is a valid way:
struct kludge : Base {
kludge(const Base& b): Base(b) {}
operator int() {
return m_attribute;
}
};
usage:
Base base(5);
int foo = kludge(base);
This kludge works by copy constructing the base sub object of the derived type. This of course depends on the base being copyable - which your Base is. It's easy to tweak to work with movable as well.
As a syntactic sugar, the kludge is implicitly convertible to the type of the member. If you prefer, you could use a getter.
if base class doesn't have a default constructor after overloading it to take some arguments and no default one is there then the derived classes must use member-initializer list to initialize the base part otherwise you cannot instantiate the derived class getting the compiler complaining about missing default constructor in base class:
class Base
{
public:
// Base(){} default constructor by default the compiler creates one for you unless you overload it so the next one taking one parameter will hide this one
Base(int data) // hides the default ctor so derived classes must use member-initializer list
: m_attribute(data) {}
protected:
int m_attribute;
};
class Derived : public Base
{
public:
Derived() : Base(0){} // you must use member intializer list to initialize the part Base
//Derived(int x) : Base(x){} // also ok
int get_attribute(){ return m_attribute; }
};
int main()
{
Derived dervObj;
Derived* derived = static_cast < Derived*>(&baseObj);
int base_attribute = derived->get_attribute();
cout << base_attribute << endl;
}
also you cannot cast the address of class base to derived object but cast an object of base class to derived one.
so in your example writing in main:
Derived* derived = static_cast < Derived*>(&baseObj); // is like writing:
char* cp = static_cast < char*>(&int); // you must convert a variable not a type
why you want to access protected members from outside??? keep in mind that public inheritance will copy all the members of base to derived class but private.
using friendship or making member data public will make it possible to access it from outside but it undermines the principles of data-hiding and encapsulation however friendship in some cases it's a must and there's no other alternative then use it carefully but making data public it's better to get back to structs
The Derived class can access and modify the public and protected Base class properties and methods.
Then, you can't case Base into Derived.
Derived inherit from Base, so Derived is a Base.
But a Base is not a Derived (a Car is a Vehicle, a Vehicle is not a Car).
So if you need a getter, put it directly into Base, or instanciate a Derived instead of a Base.
Firstly:
Derived* derived = static_cast < Base*>(base);
This is not valid and illegal. Won't compile. You can't static cast Base to Base*.
And to answer your question:
Base base(5);
Derived& derived = static_cast<Derived&>(base);
std::cout << derived.get_attribute();
Or if you want to use a pointer because you think you're cooler:
Base base(5);
Derived* derived = static_cast<Derived*>(&base);
std::cout << derived->get_attribute();
EDIT: static_cast doesn't have any overhead on runtime. It is static, hence it's a compile-time thing. Both methods will yield the same result.

forward declaring with inheritance information

This compiles fine, although I wouldn't want to try running it just yet. However ...
//class base;
//class derived;
//class derived : public base;
class base {};
class derived : public base {};
class other
{
public:
void func() {base1 = derived1;}
base* base1;
derived* derived1;
};
void main()
{
}
... moving the class other to above the definition of base and derived for which there is a similar thing I must do in a program of myne causes compile errors.
The obvious solution is to forward declare base and derived shown commented out at the top of the code, however this causes a can't convert between base* and derived* error. Attempting to forward declare including the inheritance information dosn't work either.
This should work. You need to move other up
BUT declare func below. That way func is able to "see" that derived is of type base.
e.g.,
class base;
class derived;
//class derived : public base;
class other
{
public:
void func();
base* base1;
derived* derived1;
};
class base {};
class derived : public base {};
void other::func() { base1 = derived1; }
There is no syntax for forward-declaring two classes and specifying that one inherits from the other. This is because inheritance can be complex (multiple and/or virtual), so the assignment base1 = derived1 might involve some arithmetic, and it's difficult/impossible for the compiler to generate that arithmetic when it only knows that derived inherits from base.
So, to solve your problem, you can make func not inline (see the answer from AbstractDissonance), or, if you absolutely need it to be inline, use reinterpret_cast:
class base;
class derived;
class other
{
public:
void func() {base1 = reinterpret_cast<base*>(derived1);}
base* base1;
derived* derived1;
};
This is bad because it is not guaranteed to work by the C++ standard, and it will almost certainly not work if you use multiple/virtual inheritance. Use this only if func has to be as fast as possible (i.e. inline), and if you don't need your code to be portable.

Why does Base *pd = new Derived; generate an error?

Given this code:
class Base{
public:
Base();
virtual ~Base();
};
class Derived: protected Base{
public:
virtual ~Derived();
};
In main I am trying to assign derived to base in this way:
Base *pd = new Derived;
Why is this statement generating an error?
Here new will return a pointer of the object type and we can always assign a derived pointer to a base. Correct me if I am wrong.
To convert a pointer to one class to a pointer to a different class type the conversion must be accessible at the point that it is invoked.
As Base is a protected base of Derived you can't initialize a variable of type Base * from the expression new Derived (which has type Derived *) outside of a member function of Derived, a class derived from it or a friend of Derived.
A linker error may just be the result of missing an implementations for the classes. It would help if you could post the particular error messages.

Can a pointer of a derived class be type cast to the pointer of its base class?

The pointer of derived class returned by new can be type cast to the pointer of its base class.
Is this true or false?
I know dynamic_cast can be used to cast downside. Generally, how to cast a pointer of derived class to a pointer of its base class?
Yes. Conversion from a pointer to a derived class to a pointer to a base class is implicit. Thus, the following is perfectly fine:
struct B { };
struct D : B { };
D* my_d_ptr = new D;
B* my_d_ptr_as_a_b_ptr = my_d_ptr;
Casting a pointer to a derived to a pointer to base should be implicit. This is the whole point of polymorphism: An instance of a derived class should always be safely usable as an instance of the base class. Therefore, no explicit cast is necessary.
That's true if derived class inherits 'publicly' and 'non-virtually' from base:
You can't convert Derived* to Base* neither implicitly nor using static_cast/dynamic_cast (C-cast will do the job, but you should think twice before use this hack!);
class Base { };
class Derived : protected Base { };
int main()
{
Base* b = new Derived(); // compile error
}
Also don't work if base class is ambiguous:
class Base { };
class Derived1 : public Base { };
class Derived2 : public Base { };
class MostDerived : public Derived1, Derived2 { };
int main()
{
Base* b = new MostDerived(); // won't work (but you could hint compiler
// which path to use for finding Base
}
Edit: added code samples, added ambiguous use case, removed virtual inheritance example.
Your question is not clear becuse it mixes up several different things.
On the one hand, a pointer to derived class can be converted to a pointer to a base class (assuming the base is accessible). This is a natural conversion and there's no need for any cast to do it.
On the other hand, you mention dynamic_cast and its ability to to perform downcasts. But downcasts are casts in the opposite direction: from a pointer to a base class to a pointer to derived class. Downcasts can be performed by both dynamic_cast and static_cast depending on what you need and what amount of run-time checking you require.
... And at the same time you ar talking about casting the result of new, which, of course, can only be upcasted, but not downcasted.
So, what is it you are asking about? Upcasts or downcasts?

Member Pointer to Base Class

all. I can't undestand why the bellow code need a cast to work. Someone can explain it?
class Base {
};
class Derived : public Base {
};
class Class {
public:
Derived member;
};
...
Derived obj;
Base *ptrObj = &obj; // ok, no cast needed
Derived Class::* ptr = &Class::member; // ok
Base Class::* ptr = &Class::member; // wrong, need cast, why?
Because if Base were allowed (covariant), you could then do this, which is a no-no:
Base Class::* ptr = &Class::member;
Class obj;
obj.*ptr = Base(); // <-- assigned a Base into a Derived field?!
At the same time, pointers-to-members cannot be contravariant either, because otherwise you could do this, which is also a no-no:
struct Class2 {
Base member;
};
Derived Class2::* ptr2 = &Class2::member;
Class2 obj2;
obj2.member = Base();
Derived& d = obj2.*ptr2; // <-- assigned a Base into a Derived
So, pointers-to-members are neither covariant nor contravariant, but are invariant: the type must match exactly.
Ok, I got your point Chris, but your first example works for ordinary pointers. Why should it not work for member pointers too? See the code bellow.
Derived obj;
Base *ptr = &obj;
*ptr = Base(); // it's weird, but ok
The second example will not work even for ordinary pointers, since downcasting is not allowed without cast. So I don't think that should be a explanation.