Error while accessing derived class resources by base class object - c++

I have base class called Base and a derived class of Base called Derived,
A Base Class pointer can point to a derived class object and can also access its resource but I am getting an error doing the same.
class Base
{
public:
int a;
};
class Derived : public Base
{
public:
float b;
void DoSomething()
{
cout<<"Derived";
}
};
int main()
{
Base * pBase = new Derived();
pBase->DoSomething();
pBase->a = 5;
pBase->b = 0.2f;
return 0;
}
This gives me an error
main.cpp: In function ‘int main()’:
main.cpp:34:25: error: ‘class Base’ has no member named ‘DoSomething’
pBase->DoSomething();
^
main.cpp:36:12: error: ‘class Base’ has no member named ‘b’
pBase->b = 0.2f;
^
Pardon me if its too basics, I am a beginner in c++

Yes you can use a Base pointer to a Derived class, nonetheless, the Base pointer must know the methods in order to choose what's the most suited for the call, if the Base pointer has no knowledge of the existence of these variables and functions it cannot call them.
Corrected code:
class Base
{
public:
int a;
float b;
virtual ~Base(){} //virtual destructor required
virtual void DoSomething() //implementing DoSomething in base class
{
std::cout << "Base";
}
};
class Derived : public Base
{
public:
void DoSomething() override //override DoSomething() in base class
{
std::cout<<"Derived";
}
};
Base * pBase = new Derived();
//Base will choose the most suited DoSomething(), depending where it's pointing to
pBase->DoSomething();
pBase->a = 5;
pBase->b = 0.2f;
Output:
Derived
Edit:
As you suggested in the comment section, casting the derived class will work in this specific case, but it usually reveals poorly designed code, as pointed out by #user4581301's comment, also note the link provided that has some of the reasons why this is not the best idea.
As I said, if you must do it, use dynamic_cast<>() instead.
Note that, in any case, you still need the virtual destructor for a correct implementaion of polymorphism.
Virtual destructors
Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual.
and that's not all, check this link.

Related

Invalid new-expression of abstract class type 'A'

Why does this small example:
class A {
public:
virtual void run() = 0;
};
class B : public A {
public:
void run() override {
std::cout << "Running...\n";
}
};
int main() {
std::unique_ptr<A> a = std::make_unique<A>(new B());
}
Gives me this error message:
error: invalid new-expression of abstract class type 'A'
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
because the following virtual functions are pure within 'A':
class A {
'virtual void A::run()'
virtual void run() = 0;
Is this because a unique_ptr cannot take an abstract class as argument?
Why does this small example: ... Gives me this error message: invalid new-expression of abstract
Is this because a unique_ptr cannot take an abstract class as argument?
No, it isn't. std::unique_ptr can take an abstract class as an argument.
It is because you're attempting to create an instance of A. This is not possible because A is abstract.
You may have intended instead to create an instance of B, and have the std::unique_ptr<A> take ownership of that pointer:
std::unique_ptr<A> a = std::make_unique<B>();
Note though however, that you mustn't let this pointer go out of scope, because upon destruction of a, the object would be deleted through a pointer to A, and since the pointed object is B, and destructor of A is not virtual, the behaviour would be undefined. Solution: declare A::~A virtual.

Polymorphism in C++ why is this isn't working?

class Base {
public:
virtual void f();
void f(int);
virtual ~Base();
};
class Derived : public Base {
public:
void f();
};
int main()
{
Derived *ptr = new Derived;
ptr->f(1);
delete ptr;
return 0;
}
ptr->f(1); is showing the following error: "too many arguments in function call".
Why is this isn't possible? isn't derived inherited all the functions form base and is free to use any of them?
I could call it explicitly and it would work but why isn't this allowed?
What you are seeing is called hiding.
When you override the function void f() in the Derived class, you hide all other variants of the f function in the Base class.
You can solve this with the using keyword:
class Derived : public Base {
public:
using Base::f; // Pull all `f` symbols from the base class into the scope of this class
void f() override; // Override the non-argument version
};
As mentioned by #Some Programming Dude : it is because of Hiding.
To understand hiding in relatively simpler language
Inheritance is meant to bring Baseclass variables / functions in Derived class.
But, on 1 condition : "If its not already available in Derived Class"
Since f() is already available in Derived, it doesn't make sense to look at Base class from compiler perspective.
That's the precise reason why you need to scope clarify while calling this function
void main()
{
Derived *ptr = new Derived;
ptr->Base::f(1);
delete ptr;
}
Suppose for time being that Derived do have the access to the function void Base::f(int);. Then it will be a case of function overloading. But, this is invalid case of function overloading since one function f(int);is in Base and other function f(); is in Derived. Function Overloading happens inside a single class. Function Overriding happens across classes. The example you posted is a case of Name Hiding in Inheritance
"Derived *ptr" This definition will only allow "ptr" to access all the member functions which are defined via Derived class or its child class. But, it will not allow u to access the member functions which are coming in Derived class because of inheritance.
If u want to access base class version of function "f" then use "Base *ptr" and it will choose the correct version of function automatically as shown :)
class Base {
public:
virtual void f()
{
cout<<"Here 2"<<endl;
}
void f(int x)
{
cout<<"Here 1"<<endl;
}
virtual ~Base() {}
};
class Derived : public Base {
public:
void f()
{
cout<<"Here 3"<<endl;
}
virtual ~Derived() {}
};
int main()
{
Base *ptr = new Derived;
ptr->f(1);
delete ptr;
return 0;
}
output is
Here 1

Can't access public base member from derived pointer

Why does this code not compile? (gcc 4.7.0)
// Class with a simple getter/setter pair.
class Base {
public:
Base () : m_Value(0) { }
virtual ~Base () { }
// Getter
virtual int value () { return m_Value; }
// Setter
virtual void value (int Val) { m_Value = Val; }
private:
int m_Value;
};
// Derived class overrides the setter.
class Derived : public Base {
public:
void value (int Val) {
// do some stuff here...
}
};
int main()
{
Derived * instance = new Derived();
int x = instance->value(); // ERROR
return 0;
}
Build log:
test.cpp: In function 'int main()':
test.cpp:29:25: error: no matching function for call to 'Derived::value()'
test.cpp:29:25: note: candidate is:
test.cpp:21:7: note: virtual void Derived::value(int)
test.cpp:21:7: note: candidate expects 1 argument, 0 provided
Why does the compiler fail to see 'int value()' from Base when using Derived*?
Changing
Derived * instance = new Derived();
to
Base * instance = new Derived();
works (but I need the derived pointer in my case).
Also renaming the base getter/setter functions to say getValue() and setValue(int) works. I can use various workarounds for my code, but I was just curious as to why this code fails to compile.
This is how the language works: When a child class overrides a member of a name it hides all the non-overridden names in the parent. This is to prevent accidentally combining base and parent methods that should be overridden as sets.
You can put using Base::value; in your child class to bring in the parent methods.
The function value in the derived class hides the function in the base class.
You need to bring the base class functions into the scope of the derived class as:
class Derived : public Base {
public:
using Base::value; //<---- note this
void value (int Val) {
// do some stuff here...
}
};
Besides the other answers given, in addition to adding using Base::value in the child class, you can also do the following,
int x = instance->Base::value();
Where you specifically tell the compiler to use Base's value function. Although technically this works, it forces a bit of indirection and if you see yourself doing this often you may want to rethink how you are structuring your code.

Can you override private functions defined in a base class?

I believe, a derived class can override only those functions which it inherited from the base class. Is my understanding correct.?
That is if base class has a public member function say, func, then the derived class can override the member function func.
But if the base class has a private member function say, foo, then the derived class cannot override the member function foo.
Am i right?
Edit
I have come up with a code sample after studying the answers given by SO members. I am mentioning the points which i studied as comments in the code. Hope i am right. Thanks
/* Points to ponder:
1. Irrespective of the access specifier, the member functions can be override in base class.
But we cannot directly access the overriden function. It has to be invoked using a public
member function of base class.
2. A base class pointer holding the derived class obj's address can access only those members which
the derived class inherited from the base class. */
#include <iostream>
using namespace std;
class base
{
private:
virtual void do_op()
{
cout << "This is do_op() in base which is pvt\n";
}
public:
void op()
{
do_op();
}
};
class derived: public base
{
public:
void do_op()
{
cout << "This is do_op() in derived class\n";
}
};
int main()
{
base *bptr;
derived d;
bptr = &d;
bptr->op(); /* Invoking the overriden do_op() of derived class through the public
function op() of base class */
//bptr->do_op(); /* Error. bptr trying to access a member function which derived class
did not inherit from base class */
return 0;
}
You can override functions regardless of access specifiers. That's also the heart of the non-virtual interface idiom. The only requirement is of course that they are virtual.
But if the base class has a private member function say, foo, then the derived class cannot override the member function foo.
In Java, you can't. In C++, you can.
You are correct in that to override a function in a derived class, it must inherit it from the base class (in addition, the base class function must be virtual). However you are wrong about your assumption that virtual functions are not inherited. For example, the following works well (and is actually a known idiom for precondition/postcondition checking):
class Base
{
public:
void operate_on(some thing);
private:
virtual void do_operate_on(some thing) = 0;
};
void Base::operate_on(some thing)
{
// check preconditions
do_operate_on(thing);
// check postconditions
}
class Derived: public Base
{
// this overrides Base::do_operate_on
void do_operate_on(some thing);
};
void Derived::do_operate_on(some thing)
{
// do something
}
int main()
{
some thing;
Base* p = new Derived;
// this calls Base::operate_on, which in turn calls the overridden
// Derived::do_operate_on, not Base::do_operate_on (which doesn't have an
// implementation anyway)
p->operate_on(thing);
delete p;
}
A way to see that private methods are really inherited is to look at the error messages generated by the following code:
class Base
{
private:
void private_method_of_B();
};
class Derived:
public Base
{
};
int main()
{
Derived d;
d.private_method_of_B();
d.method_that_does_not_exist();
}
Trying to compile this with g++ leads tot he following error messages:
privatemethodinheritance.cc: In function 'int main()':
privatemethodinheritance.cc:4: error: 'void Base::private_method_of_B()' is private
privatemethodinheritance.cc:15: error: within this context
privatemethodinheritance.cc:16: error: 'class Derived' has no member named 'method_that_does_not_exist'
If class Derived wouldn't inherit that function, the error message would be the same in both cases.
No You can not over ride any function in base class .
My reason for this notion is that if you define the function in derived class that has the same function signiture in base class , the base class function will become hidden for derived class .
For more information about this exciting issue just visit :
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Foverload_member_fn_base_derived.htm
It's also depends on the type of inheritance
class Derived : [public | protected | private] Base { };
In order to override a function inherited from base class, it should be both virtual, and classified as public or protected.

Access to method pointer to protected method?

This code:
class B {
protected:
void Foo(){}
}
class D : public B {
public:
void Baz() {
Foo();
}
void Bar() {
printf("%x\n", &B::Foo);
}
}
gives this error:
t.cpp: In member function 'void D::Bar()':
Line 3: error: 'void B::Foo()' is protected
Why can I call a protected method but not take its address?
Is there a way to mark something fully accessible from derived classes rather than only accessible from derived classes and in relation to said derived class?
BTW: This looks related but what I'm looking for a reference to where this is called out in the spec or the like (and hopefully that will lead to how to get things to work the way I was expecting).
You can take the address through D by writing &D::Foo, instead of &B::Foo.
See this compiles fine : http://www.ideone.com/22bM4
But this doesn't compile (your code) : http://www.ideone.com/OpxUy
Why can I call a protected method but not take its address?
You cannot take its address by writing &B::Foo because Foo is a protected member, you cannot access it from outside B, not even its address. But writing &D::Foo, you can, because Foo becomes a member of D through inheritance, and you can get its address, no matter whether its private, protected or public.
&B::Foo has same restriction as b.Foo() and pB->Foo() has, in the following code:
void Bar() {
B b;
b.Foo(); //error - cannot access protected member!
B *pB = this;
pB->Foo(); //error - cannot access protected member!
}
See error at ideone : http://www.ideone.com/P26JT
This is because an object of a derived class can only access protected members of a base class if it's the same object. Allowing you to take the pointer of a protected member function would make it impossible to maintain this restriction, as function pointers do not carry any of this information with them.
I believe protected doesn't work the way you think it does in C++. In C++ protected only allows access to parent members of its own instance NOT arbitrary instances of the parent class. As noted in other answers, taking the address of a parent function would violate this.
If you want access to arbitrary instances of a parent, you could have the parent class friend the child, or make the parent method public. There's no way to change the meaning of protected to do what you want it to do within a C++ program.
But what are you really trying to do here? Maybe we can solve that problem for you.
Why can I call a protected method but not take its address?
This question has an error. You cannot do a call either
B *self = this;
self->Foo(); // error either!
As another answer says if you access the non-static protected member by a D, then you can. Maybe you want to read this?
As a summary, read this issue report.
Your post doesn't answer "Why can I
call a protected method but not take
its address?"
class D : public B {
public:
void Baz() {
// this line
Foo();
// is shorthand for:
this->Foo();
}
void Bar() {
// this line isn't, it's taking the address of B::Foo
printf("%x\n", &B::Foo);
// not D:Foo, which would work
printf("%x\n", &D::Foo);
}
}
Is there a way to mark something fully accessible from derived classes rather than only accessible from derived classes and in relation to said derived class?
Yes, with the passkey idiom. :)
class derived_key
{
// Both private.
friend class derived;
derived_key() {}
};
class base
{
public:
void foo(derived_key) {}
};
class derived : public base
{
public:
void bar() { foo(derived_key()); }
};
Since only derived has access to the contructor of derived_key, only that class can call the foo method, even though it's public.
The obvious problem with that approach is the fact, that you need to friend every possible derived class, which is pretty error prone. Another possible (and imho better way in your case) is to friend the base class and expose a protected get_key method.
class base_key
{
friend class base;
base_key() {}
};
class base
{
public:
void foo(base_key) {}
protected:
base_key get_key() const { return base_key(); }
};
class derived1 : public base
{
public:
void bar() { foo(get_key()); }
};
class derived2 : public base
{
public:
void baz() { foo(get_key()); }
};
int main()
{
derived1 d1;
d1.bar(); // works
d1.foo(base_key()); // error: base_key ctor inaccessible
d1.foo(d1.get_key()); // error: get_key inaccessible
derived2 d2;
d2.baz(); // works again
}
See the full example on Ideone.
Standard reference: https://en.cppreference.com/w/cpp/language/access#Protected_member_access
When a pointer to a protected member is formed, it must use a derived class in its declaration:
struct Base {
protected:
int i;
};
struct Derived : Base {
void f() {
// int Base::* ptr = &Base::i; // error: must name using Derived
int Base::* ptr = &Derived::i; // OK
}
};