I have a problem with inheritance in C++. The attached code produces the output "1,1," but I thought the action methods from the classes b and c replace the action method from class a. So I expected the output "2,3,". What do I have to change to get the output "2,3,"?
#include <iostream>
//Class a
class a
{
public:
a();
int action();
};
a::a()
{
}
int a::action()
{
return 1;
}
//Class b
class b : public a
{
public:
b();
int action();
};
b::b()
{
}
int b::action()
{
return 2;
}
//Class c
class c : public a
{
public:
c();
int action();
};
c::c()
{
}
int c::action()
{
return 3;
}
//Main Programm
int main()
{
a arr[2];
arr[0] = b();
arr[1] = c();
for(int i = 0; i<2; i++)
{
std::cout << arr[0].action() << ",";
}
return 0;
}
Action needs to be virtual in the base class, otherwise you can't override it.
You can use the foo() override notation to get a compile-time check as to whether you're really overriding something.
You will have to access the derived type trough a pointer to the base type, otherwise you'll slice and do other nasty things. Also sometimes it's a good idea to also make your destructor virtual.
class Base { };
class Derived : public Base { };
some_container<Base*> baseOrDerived;
Then you can allocate both Base and Derived objects into this container. For example with new, although you probably want to use std::shared_ptr<Base> or std::unique_ptr<Base> instead of Base*.
you can use virtual function to get the output "2,3":
first, you should change void action(); to virtual void action(); in class a;
second, you should use pointer to implement polymorphism;
third, you should change arr[0] to arr[i];
Here is my code:
#include <iostream>
//Class a
class a
{
public:
a();
virtual int action();
};
a::a()
{
}
int a::action()
{
return 1;
}
//Class b
class b : public a
{
public:
b();
int action();
};
b::b()
{
}
int b::action()
{
return 2;
}
//Class c
class c : public a
{
public:
c();
int action();
};
c::c()
{
}
int c::action()
{
return 3;
}
int main(int argc, char *argv[])
{
a *(arr[2]);
arr[0] = new b();
arr[1] = new c();
for(int i = 0; i<2; i++)
{
std::cout << arr[i]->action() << ",";
}
return 0;
}
Here is my output:
Related
In the virtual method create() in the derived class Derived, I return a struct of type HelpDerived. However, since I had to set the return type of the method to HelpBase, I found that I need to cast the returned object back to the type HelpDerived.
The following is an example of my case.
#include <iostream>
struct HelpBase {
int a = 0;
virtual void output() {}
};
struct HelpDerived : HelpBase {
int b = 0;
void output() override {}
};
class Base {
public:
virtual HelpBase create() = 0;
};
class Derived : public Base {
public:
HelpBase create() override;
};
HelpBase Derived::create() {
HelpDerived d;
d.a = 1;
d.b = 2;
return d;
}
int main() {
Derived d;
auto based = d.create();
HelpDerived derived = dynamic_cast<HelpDerived &>(based);
std::cout << derived.a << std::endl;
}
When I run the code abve, I get the error
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
Abort trap: 6
What have I misunderstood about objects and casting in C++? Why does this method not work?
What can I do to fix the problem?
I think you'd better return a pointer to avoid object slicing in your create function.
#include <iostream>
struct HelpBase {
int a = 0;
virtual void output() {}
};
struct HelpDerived : HelpBase {
int b = 0;
void output() override {}
};
class Base {
public:
virtual HelpBase* create() = 0;
};
class Derived : public Base {
public:
HelpBase* create() override;
};
HelpBase* Derived::create() {
HelpDerived* d = new HelpDerived;
d->a = 1;
d->b = 2;
return d;
}
int main() {
Derived d;
auto based = d.create();
HelpDerived* derived = dynamic_cast<HelpDerived *>(based);
std::cout << derived->a << " " << derived->b << std::endl;
delete derived;
}
I've replaced dynamic cast by static cast and it worked for me almost fine.
#include <iostream>
struct HelpBase {
int a = 0;
virtual void output() {}
};
struct HelpDerived : HelpBase {
int b = 0;
void output() override {}
};
class Base {
public:
virtual HelpBase create() = 0;
};
class Derived : public Base {
public:
HelpBase create() override;
};
HelpBase Derived::create() {
HelpDerived d;
d.a = 3;
d.b = 2;
return d;
}
int main() {
Derived d;
auto based = d.create();
HelpDerived derived = static_cast<HelpDerived &>(based);
std::cout << derived.a << std::endl;
std::cout << derived.b << std::endl;
}
Output:
3
32726
Note that a value is correct, while b is junk. This is because for derived constructor has not been called.
In general, casting from base class to derived is not recommended, as derived may have more data members, than base class.
Recommended reading: https://www.bogotobogo.com/cplusplus/upcasting_downcasting.php
I have a class derived from an interface and a friend class of the derived class. I want to access the members of derived class which is instantiated as interface. It looks like this:
Interface:
class AInterface
{
public:
virtual ~AInterface() = default;
virtual void set(int a) = 0;
};
Derived class A with friend class B:
class B;
class A : public AInterface
{
public:
~A() override {}
void set(int a) override
{
mem = a;
}
private:
friend class B;
int mem = 0;
};
class B:
class B
{
public:
B()
{
a = new A();
a->set(3);
}
int get_a()
{
// Access mem since it's a friend class
return a->mem;
}
private:
AInterface *a;
}
main:
int main()
{
B *b = new B();
std::cout << b->get_a() << std::endl;
return 0;
}
The program does not compile saying AInterface has no member named 'mem'.
Do I need getter functions in the interface and implement it in A to achieve this or is there any other way to do it?
Now work
#include <iostream>
using namespace std;
class AInterface
{
public:
virtual ~AInterface() = default;
int getMem() { return mem; }
virtual void set(int a) = 0;
protected:
int mem = 0;
};
class A : public AInterface
{
public:
~A() override {}
void set(int a) override
{
mem = a;
}
};
class B
{
public:
B()
{
a = new A{};
a->set(3);
}
int get_a()
{
// Access mem since it's a friend class
return a->getMem();
}
private:
AInterface *a;
};
int main()
{
B *b = new B();
std::cout << b->get_a() << std::endl;
return 0;
}
Method which is override by child and is pure, should be virtual.
If each class (child) Interface, variable int mem should be protected in interface.
Now works fine, like you want.
Add getter getMem()
Version with friend
#include <iostream>
using namespace std;
class AInterface
{
public:
virtual ~AInterface() = default;
virtual void set(int a) = 0;
protected:
friend class B;
int mem = 0;
};
class A : public AInterface
{
public:
~A() override {}
void set(int a) override
{
mem = a;
}
};
class B
{
public:
B()
{
a = new A{};
a->set(3);
}
int get_a()
{
// Access mem since it's a friend class
return a->mem;
}
private:
AInterface *a;
};
int main()
{
B *b = new B();
std::cout << b->get_a() << std::endl;
return 0;
}
In your class B.
class B
{
//...
int get_a()
{
return a->mem; // but a is a AInterface* !!!
}
private:
AInterface *a; // That's not an A*, but an AInterface*
};
You have 2 options.
use dynamic_cast<>
int B::get_a()
{
A* p = dynamic_cast<A*>(a);
if (p)
return p->mem;
// a is not an A*, it's another AInterface*-type object !!!
// What should you do?
throw something_or_other(); // throw?
return -1; // return an error code?
}
// or maybe add.. so you can check for errors before calling get_a()
A* B::get_A_ptr() const
{
return dynamic_cast<A*>(a);
}
dynamic_cast works fine, but can slow down your app if you need to make frequent reads of a->mem.
Store a in an A*, which is probably what you meant to do from the start...
class B
{
// ...
private:
A* a; // now a->A::mem is visible.
};
Since you explicitly call new A in B's constructor, I think option 2 is better for your case.
I would like to create an hierarchy of classes in c++ so public variables of higher level classes were visible within lower level classes. Here is an example, the desired action is in "printf" of two constructors. As is now, variable a cannot be seen within class Local1. How to fix it? In general, classes will be defined in different files. Thank you.
class Global
{
int a;
Local1 l1;
}
class Local1
{
int b;
Local2 l2;
Local1(){printf("%i", a);}; #constructor
}
class Local2
{
Local2(){printf("%i, %i", a, b);}; #constructor
}
main()
{
Global g;
# want to create objects g, l1, l2, and print values of a and a,b
}
You could use inheritance.
Local2 inherits from Local1.
Local1 inherits from Global.
class Global
{
public:
int getA() {
return a;
}
virtual void doStuff() {
// do stuff
}
private:
int a;
};
class Local1 : public Global
{
public:
Local1(){
printf("%i", getA());
}
int getB() {
return b;
}
private:
int b;
};
class Local2 : public Local1
{
public:
Local2(){
printf("%i, %i", getA(), getB());
}
virtual void doStuff() override {
// do specific stuff
}
};
int _tmain(int argc, _TCHAR* argv[])
{
auto g = std::unique_ptr<Global>(new Local2());
g->doStuff(); // will call Local2::doStuff
}
Can't you simply pass to the child a pointer to the parent, like in the following naïve example?
#include<memory>
#include<iostream>
struct P {
struct C {
C(P *parent): p{parent} { }
void foo() {
std::cout << p->i << std::endl;
}
P *p;
};
int i;
C c{this};
};
int main() {
P p;
p.i = 42;
p.c.foo();
}
My scenario is simplified in the following example:
#include <iostream>
#include <vector>
using namespace std;
class C;
class A
{
protected:
C * cPointer;
A();
virtual void updateList() = 0;
void callFunc();
};
class B : public A
{
private:
vector<int> list;
void updateList();
public:
void callFromA();
};
class C
{
friend class A;
friend class B; // I want to get rid off this declaration
private:
int sum;
void set_sum( int val );
public:
static C * getCPointer();
};
A::A()
{
cPointer = C::getCPointer();
}
void A::callFunc()
{
updateList();
}
void B::updateList()
{
list.push_back(2);
list.push_back(4);
int s = 0;
for( unsigned int i=0; i<list.size(); i++ )
{
s += list[i];
}
cPointer->set_sum(s);
}
void B::callFromA()
{
callFunc();
}
void C::set_sum( int val )
{
sum = val;
cout << "Sum at C is: " << sum << endl;
}
C * C::getCPointer()
{
static C cPointer;
return & cPointer;
}
int main( int argc, char ** argv)
{
B b;
b.callFromA();
return 0;
}
This example works fine. But I want to get rid of the "friend class B" declaration in class C and achieving similar functionality. Actually I want to have either of the following:
accessibility of C::set_sum() from B::updateList() which will not be possible without the "friend class B" declaration in class C.
accessibility of B::list in A::callFunc() whereby I can push the logic from B::updateList to A::callFunc() which basically means ability to access a list in the derived class from the base class. In this way, I will be able to access the set_sum() in A::callFunc() due to "friend class A" declaration in class C.
Any idea to achieve this without involving major design changes is desirable!
Thanks!
I'm not sure if I understand all your restrictions, but maybe this works better for you. Basically, you can access B::list from A using a virtual function. I've commented the changes in the code.
#include <iostream>
#include <vector>
using namespace std;
class A;
class C
{
friend class A;
private:
int sum;
void set_sum(int val);
public:
static C * getCPointer();
};
class A
{
protected:
C * cPointer;
A();
virtual int getS() = 0; // virtual function to calculate data from vector in derived class B
virtual void updateList()
{
cPointer->set_sum(getS()); // A is friend of C, so you can access B data from A
}
void callFunc();
};
class B : public A
{
private:
vector<int> list;
void updateList();
int getS() // concrete implementation to access vector data
{
int s = 0;
for (unsigned int i = 0; i < list.size(); i++)
{
s += list[i];
}
return s;
}
public:
void callFromA();
};
A::A()
{
cPointer = C::getCPointer();
}
void A::callFunc()
{
updateList();
}
void B::updateList()
{
list.push_back(2);
list.push_back(4);
A::updateList(); // Call to super implementation
}
void B::callFromA()
{
callFunc();
}
void C::set_sum(int val)
{
sum = val;
cout << "Sum at C is: " << sum << endl;
}
C * C::getCPointer()
{
static C cPointer;
return &cPointer;
}
int main(int argc, char ** argv)
{
B b;
b.callFromA();
return 0;
}
You can not access members of derived classes inside the base class, period. The object at hand might be of the base class, or even of a completely unrelated derived class, with guaranteed "interesting" consecuences. Any design asking for doing so is seriously broken, and needs rethinking.
You can make the member function of the base class which wants to do so virtual, and redefine it in the derived class to do whatever perversion you have in mind. Meanwhile, the chaste member of the base class can just refuse if called, signalling the mistake in a sane way. That way you get a guarantee that nothing too untoward can happen.
I am trying to do something like this with c++.
void showContensofArray(void *data[])
{
//In this function have to display the values of respective objects.
// Any ideas how do I do it?
}
int main(){
A phew(xxx,abcdefg); //object of class A
B ball(90),ball2(88); //object of class B
void *dataArray[2];
dataArray[0] = &ph1;
dataArray[1] = &ball;
showContentsofArray(dataArray); //function
}
If you want to treat the objects in the data[] generically (i.e by calling a common function on them to extract a description or values) then define a class hirachy for your objects and in your showContentsofArray function call virtual methods on your (common base class) object pointers.
This is a textbook example of Polymorphism:
"polymorphism allows values of different data types to be handled using a uniform interface."
In the example below the base class BaseObject defines the uniform interface.
class BaseObject {
virtual string description() { return "Base object"; }
virtual bool bounces() { return false; }
}
class B : public BaseObject {
string description() { return "Im a B object" }
bool bounces() { return true; }
}
class A : public BaseObject {
string description() { return "Im an A object" }
}
void showContensofArray(BaseObject* data[], int size) {
for (int i=0; i<size; i++) {
cout << data[i]->description();
if (data[i]->bounces())
cout << "I bounce!";
}
}
int main() {
A phew(xxx,abcdefg); //object of class A
B ball(90),ball2(88); //object of class B
BaseObject* dataArray[2];
dataArray[0] = &ph1;
dataArray[1] = &ball;
showContentsofArray(dataArray);
}
Will output:
Im an A object
Im a B object
I bounce!
void showContensofArray(void *data[], int len)
{
int i;
for(i=0;i<len;i++){
((Base*)(data[i]))->print();
}
}
And every Class should have an implementation of the method print() that knows how to print its values.
You could also use inheritance.
EDIT:
#Ricibob's answer is correct, but if you need to do the casting inside the function, you need to do something like this:
#include <iostream>
using namespace std;
class Base{
public:
virtual void print()=0;
};
class A: public Base{
public:
void print(){
cout<<"Object A"<<endl;
}
};
class B: public Base{
public:
void print(){
cout<<"Object B"<<endl;
}
};
void showContensofArray(void* data[], int len)
{
int i;
for(i=0;i<len;i++){
((Base*)(data[i]))->print();
}
}
int main(){
A a;
B b;
void* v[2];
v[0]= &a;
v[1] = &b;
showContensofArray(v,2);
return 0;
}
You can't evade inheritance.
Just cast back to the original type:
A* p1 = static_cast<A*>(data[0]);
B* p2 = static_cast<B*>(data[1]);