c++ : How to bind inherited methods only to parent classes? - c++

i've stumbled upon this problem while doing multi-base inheritance project for my college work. Example of my problem, and code itself: I'm setting up 3 classes, A, B and C.
B inherits publicly from A.
C inherits publicly from B.
I want to set a method publicly in B, that does take as argument a pointer to an object of class A. However it should be able to use only class A objects, neither B or C.
Problem is that Visual Studio 2013 doesn't show any error, and simply allows for my method to be used by B class object on a C class object, which is exactly the opposite of what i want to achieve. Why is that happening?
Does that mean that inheriting somewhat makes C object being interpreted as of type A, B and C at the same time? If not, is there a direct way to bind a method to be used only on classes that it inherits from (c methods on both A and B objects)? Feel free to correct me if i'm wrong anywhere, i'm still a newbie at programing. Thank you for your help! `
class A
{
private:
int x;
string z;
public:
void SetZ()
{
cout << "Set Z: ";
cin >> z;
}
string GetZ()
{
return this->z;
}
};
class B
:public A
{
public:
void use_base(A* k)
{
cout << "here and now, i'm using " << k->GetZ() << " however i, " << this->GetZ() << ", might want to!";
}
};
class C
:public B
{
void use_base(A* k)
{
cout << "extra";
}
};
int main()
{
A Bob;
B Mark;
Bob.SetZ();
Mark.SetZ();
C Karl;
Mark.use_base(&Karl); // doesn't show any error
return 0;
}`

If B inherits publicly from A, then B* can be implicitly converted to A* so a function that takes A* can be called with B* arguments. To prevent this, you could make the inheritance protected or private. However, that might create other problems.
To prevent accidentally passing a B*, you can declare another overload that takes B* and delete it. This overload will win for B* and C* arguments and cause a compilation error. You can also generalize this approach using templates, and so prevent passing a pointer to any class derived from A, without naming all such classes.
void use_base(A* k) { /* do something */ }
void use_base(B*) = delete;
However, that doesn't stop someone from explicitly casting a B* or C* to A* and calling the A* overload.

Related

I try understand How how method Overriding work, couldn't figure why is outputting 2

Here is the code
,it is my homework using overriden methods teacher told us to analyze the code. I know the code is outputting 2, I have no clue how this code work.
public:
int a;
virtual void who(void) { a = 1; }
};
class B:public A{
public:
int a;
void who(void) { a = 2; }
};
class C :public B {
};
int main(void) {
A x; B y; C z; A *p;
p = &z;
p->who();
cout << z.a << endl;
system("pause");
return 0;
}
B overrides the who() function of its parent, A. This is called polymorphism. C inherits from B, but doesn't override anything; thus, it uses all of the implementation of B.
p is a pointer to an object of class A. One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer to its base class [1].
This means that when you call a member function of a pointer (p->who()), and the class of the object the pointer is pointing to overrides a member of its parent, is going to use the overridden member.
Sources:
[1] http://www.cplusplus.com/doc/tutorial/polymorphism/
as long as you create a function with same input and output with name; in short: same function declaration.. the new one will be used as you refer to one which has super class that has same function. in your case; super class for C is B and it doesn't see A, but B sees A and use all functions it has except what's B declare a new implementation for.

How to distinguish objects of derived classes C++

Look at following code:
class A
{
protected:
int aa = 1;
};
class B : public A
{
private:
int bb = 2;
public:
int getbb() { return bb; }
};
class C : public A
{
private:
int cc = 3;
public:
int getcc() { return cc; }
};
int main()
{
std::vector<A> a;
B b;
C c;
a.push_back(b);
a.push_back(c);
a[0].getbb(); //getbb() unaccessible;
a[1].getcc(); //getcc() unaccessible;
}
A is the based class. B and C is the derived classes. I want to set a vector to hold either B or C, and use vector a to hold A. However, since a is a vector containing A's objects, I can't access methods in B and C. Is there anyway to make a[0].getbb() and a[1].getcc() work?
Your vector of A is not capable of holding Bs or Cs, because it stores A by value, resulting in object slicing when B or C is stored. In particular, this means that when you store B, only aa gets stored; bb gets sliced away.
In order to store subclasses without slicing use a container of pointers - preferably, of smart pointers.
This wouldn't help you access functionality specific to B or C without a cast. One way to solve this problem is to give virtual member functions for B's and C's functionality to A, and make calls through A-typed reference of B or C.
Not without invoking undefined behaviour.
The problem is that a.push_back(b) and a.push_back(c) do not append objects b and c to the vector. They create instances of A that hold only the "A parts". This is called object slicing.
So there is no object of type B and no object of type C in the vector.
You force the issue and make your code compile by doing something like
static_cast<B &>(a[0]).getbb();
but this just has undefined behaviour, since it treats a[0] as being of type B when it is really of type A. Which makes it a really bad idea. Although it will (probably) compile, it could do anything - and probably not what you expect.
If your vector contains A * rather than A it is possible. For example;
int main()
{
std::vector<A *> a;
a.push_back(new B);
a.push_back(new C);
B* b = dynamic_cast<B *>(a[0]);
if (b) // if a[0] actually points at a B ....
b->getbb();
else
complain_bitterly();
C *c = dynamic_cast<C *>(a[1]);
if (c)
c->getcc();
else
complain_bitterly();
}
Of course, doing this has practical trap doors as well - such as requiring class A having at least one virtual member. It would be better off to work with a polymorphic base, and override virtual functions.
In other words, your design is broken, so fix it so it doesn't somehow require you to morph an object to a different type.
An alternative to using pointers is to use a vector of std::reference_wrappers and polymorphic classes. Small example below:
#include <functional> // for std::reference_wrapper
#include <iostream>
#include <vector>
class A
{
public:
virtual void printme()
{
std::cout << "A" << std::endl;
}
virtual ~A() = default;
};
class B: public A
{
public:
void printme() override
{
std::cout << "B" << std::endl;
}
};
class C: public A
{
public:
void printme() override
{
std::cout << "C" << std::endl;
}
};
int main()
{
std::vector<std::reference_wrapper<A>> a;
B b;
C c;
a.emplace_back(b);
a.emplace_back(c);
a[0].get().printme(); // need to "get()" the raw reference
a[1].get().printme();
}
Live on Coliru
According the the cpp reference, there seems to be a way to achieve this by using dynamic_cast. You first need to make your vector a vector of pointers to the base class A. Then when accessing any element, you can check if it is a B* (or a C*) by checking the result of the dynamic_cast operator.
From the CPP reference:
dynamic_cast < new_type > ( expression )
... If the cast is successful, dynamic_cast returns a value of type new_type. If the cast fails and new_type is a pointer type, it returns a null pointer of that type...
Accordingly, you can do this:
std::vector<A*> a;
B b;
C c;
a.push_back(&b);
a.push_back(&c);
...
int i = something;
B* pB = dynamic_cast<B*>(a[i]); if(pB != nullptr) pb->getbb();
C* pC = dynamic_cast<C*>(a[i]); if(pC != nullptr) pC->getcc();
p.s: It is highly questionable as design approach though. The recommended OOP approach would be certainly to use a virtual method in the base class A and override it in B and C. But (hopefully) this answers the exact question as stated in the title.
If you're sure they're instances of B and C, use cast:
static_cast<B>(a[0]).getbb();
static_cast<C>(a[1]).getcc();
OK, you may also create a vector of A*:
std::vector<A*> as;
as.push_back(new B);
as.push_back(new C);
B* b = (B*) as[0];
b->getbb();
c->getcc();
Now you only have to remember about freeing objects with delete.
You may use "Type IDs":
class A {
// ...
virtual int getTypeID() { return 0; }
}
class B {
// ...
virtual int getTypeID() { return 1; }
}
// analogically for C
It's virtual but is in prototype of A
Now use:
switch(a.getTypeID()) {
case 0:
// It's normal A
break;
case 1:
// It's B
// ...
break;
case 2:
// It's C
// ...
break;
}

Partially hidden inheritance tree

I have a class tree as such:
class A;
class B : public A;
I then want to create a class which is derived from class B. But I want that derivation to be hidden from outside members as well as anyone else that inherits from class C
class C : private B;
void test() {
C c;
B *b = &c; // compiler error: B in C is private and is therefore not type compatible. This is desired.
}
However, I also want to reveal the inheritance of class A. Hiding class B in this case also hides class A.
void test2() {
C c;
A *a = &c; // Compiler error: A is only accessible through B which is not possible with a private inheritance of B. This is not desired; this conversion should be possible.
}
I could inherit from A again, but that would obviously create duplicate member variables if A has any. I could create a virtual inheritance of class A, however I don't feel it would have the exact effect I desire since that would affect the entire tree rather than this segment (right?)
I suppose the obvious solution would be to create a typecasting member function:
class C : private B {
A * turn_into_A() {
// Since B is an A and we are still in the scope of C, this will succeed
return this;
}
};
However, I'd prefer to avoid explicit typecasts such as that case,
Any sane person might tell me I'm doing this wrong. They'd probably be right. But I would like to know simply for knowledge's sake: is there a way to do this without virtual inheritance or an explicit member function's typecast?
I found a workable solution:
class A {
public:
void somethingA() {
std::cout << "a" << std::endl;
return;
}
};
class B :
public A {
public:
void somethingB() {
std::cout << "b" << std::endl;
return;
}
};
class C :
private B {
public:
using B::A; // While B is private (and hidden), this exposes access to B::A
void somethingC() {
std::cout << "c" << std::endl;
return;
}
};
int main(int argc, char **argv) {
C c;
B* b = &c; // Compiler error: cannot convert because B is private (desired)
A* a = &c; // Okay! (required)
c.somethingC();
c.somethingB(); // Compiler error: private. (desired)
c.somethingA(); // Compiler error: A is exposed, but not A's members. This can be solved by adding 'using B::A::somethingA()' in class declaration (undesired but acceptable in my situation)
a->somethingA(); // Okay! (of course)
}
It's not perfect in that it only exposes C to be able to be converted to A (which for my purposes is what I'll end up doing anyway, so that's fine). However it doesn't directly expose the members of A to allow C to be used as-an-A, eg you cannot call c::somethingA() unless you specifically also expose B::A::somethingA.
Inheritance depicts a IS-A relationship. So, in your object model, B IS-A A, C IS-A B. So, why don't you use
class C : public B { ...};
So that you may view a C object as a B object as well as an A object as need be. Hope that helps.

c++ inheritance abstract function?

I have a somewhat basic question on inheritance that i can seem to figure out, I've done a search and not found what I was looking for so I thought I'd ask here (not sure if title of what I'm looking for is correct).
To keep things simple I've made a bit of example code to illustrate what I'm not getting.
Basically if I have a parent class A and two child classes B & C,
where A contains common stuff (say an id with get/set),
while B & C have functions that are class specific.
If you declare a class B like: A *bObject = new B();
how do you then access the class specific functionbObj->specific()`?
I've tried virtual but that requires both B & C to have the same function name / prototype declared.
I've also tried declaring the abstract in A, but that requires it to be prototype to be in A.
Where am i going wrong here? any help on this, probably basic issue would be helpful.
#include <iostream>
using namespace std;
// A class dec
class A
{
public:
A(void);
~A(void);
char id;
void setId(char id);
char getId();
};
// B class dec - child of A
class B :
public A
{
public:
B(void);
~B(void);
void sayHello();
};
//C class dec - child of A
class C :
public A
{
public:
C(void);
~C(void);
void sayGoodby();
};
//a stuff
A::A(void)
{
}
A::~A(void)
{
}
void A::setId(char id)
{
this->id = id;
}
char A::getId()
{
return this->id;
}
//b stuff
B::B(void)
{
this->setId('b');
}
B::~B(void)
{
}
// c stuff
C::C(void)
{
this->setId('c');
}
C::~C(void)
{
}
void C::sayGoodby()
{
std::cout << "Im Only In C" << std::endl;
}
// main
void main ()
{
A *bobj = new B();
A* cobj = new C();
std::cout << "im class: " << bobj->getId() << endl;
bobj->sayHello(); // A has no member sayHello
std::cout << "im class: " << cobj->getId() << endl;
cobj->sayGoodby(); // A has no member sayGoodby
system("PAUSE");
}
Thank you for your time!
To access methods unique to a derived class, you need to cast the base class pointer to the correct derived class type first (a downcast):
A *bobj = new B();
bobj->sayHello(); // compile error
dynamic_cast<B*>(bobj)->sayHello(); // works
dynamic_cast<C*>(bobj)->sayGoodbye(); // run-time error - probably crashes with a segfault/access violation.
dynamic_cast ensures run-time type safety but adds a small overhead to the cast; for pointer casts, it returns a null pointer if the pointed-to object is not actually a B, and you should check the return value before using it. Alternatively, if you are really sure that the pointer you are casting is pointing to the correct object, you can use static_cast which saves you the cost of the run-time checking, but if the pointer is not pointing to the right object, you get undefined behavior.
A *bobj = new B();
A* cobj = new C();
Here instance of B and C is pointed by pointer of A. Since A have no virtual function for B and C's member function sayHello() and sayGoodbye(), they could not called by bobj->sayHello() and cobj->sayGoodbye(). It is not what polymorphism should be do.
Class A should be:
class A
{
public:
A(void);
~A(void);
char id;
void setId(char id);
char getId();
virtual void sayHello(){/* to do */ };
virtual void sayGoodbye(){ /* to do */ };
};
Then the bobj->sayHello(); and cobj->sayGoodbye(); could be called without complaning.
A *bobj = new B();
The static type of bobj is A *. So, at compile time, the compiler looks for the member functions in the class A definition, what ever you tried to access through bobj. Now,
bobj->sayHello();
the compiler will look for the sayHello in class A since the type of bobj is A *. Compiler doesn't care to look into the class B definition to resolve the call. Since the compiler didn't find it sayHello member in A, it is complaining.
However, the dynamic type of bobj is B * and that is a where call is dispatched depending on the dynamic type.
To resolve the issue, you need to virtual functions of the same in class A.
if you really want to call a function like this, you can do like this:
A* bobj = new B();
((B*)bobj)->sayHello();//this can be dangerous if bobj is not an instance of class B
however, the problem here is you do the design wrongly.
basically, if you create an class A, and subclass it to B and C.
And then assign A* bobj = new B(); you are splitting the interfaces and implementations. That means you will use bobj as if it is an instance of class A. and you will not call the functions in B or C. B & C are implementations of interface class A.
it's just like you hire someone to build your house. You give them your blueprint(interfaces) and hire them to build. you can alter the blueprint as you like, they will do whatever in blueprint. but you can't order them directly(just like you can't call the sayHello() directly from bobj).
You can use a down cast via dynamic_cast<>. You can implement a template method in your base class A to facilitate the down cast:
class A
{
public:
A(void);
virtual ~A(void);
char id;
void setId(char id);
char getId();
template <typename CHILD, typename R, typename... ARGS>
R invoke (R (CHILD::*m)(ARGS...), ARGS... args) {
CHILD *child = dynamic_cast<CHILD *>(this);
if (child) return (child->*m)(args...);
std::cout << "down cast error: " << typeid(CHILD).name() << std::endl;
}
};
If that particular instance of A was not the base of CHILD, then dynamic_cast<CHILD *>(this) result in NULL. Note that the virtual destructor in A is required for the dynamic_cast<> to work.
So, you can use it like this:
std::unique_ptr<A> bobj(new B());
std::unique_ptr<A> cobj(new C());
bobj->invoke(&B::sayHello);
bobj->invoke(&C::sayGoodbye);
cobj->invoke(&B::sayHello);
cobj->invoke(&C::sayGoodbye);
Only the first and last invocations are valid. The middle two will cause the "down cast error" message to be printed.

c++ inherit virtual functions

ok say we have the following classes
class A
{
public:
virtual void taco()
{
cout << "Class A" << endl;
}
};
class B: public A
{
public:
virtual void taco()
{
cout << "Class B" << endl;
}
};
class C : public A
{
public:
void taco()
{
cout << "Class C" << endl;
}
};
Now if I do this
A a = A();
B b = B();
C c = C();
a.taco(); //Class A
b.taco(); //Class B
c.taco(); //Class C
deque<A> aa = deque<A>();
aa.push_back(a);
aa.push_back(b);
aa.push_back(c);
for(int i=0;i<aa.size();i++)
aa[i].taco();//All Class A
A r = B();
r.taco(); //Class A
Now you'll notice when I initialize A as B or C, it won't fire the functions from B or C. I was wondering if there was any way around this? I understand the concept that since the object is A it uses A's taco function, but I was just wondering if there was some trick to getting at the other functions. My project is fairly complicated, and I can't know all the classes that will override A(due to plugins overriding a class). Also, I kinda need to have the base virtual function have a body to add default behavior. Thanks.
You must store pointers in the deque, since polymorphism only works with reference & pointer types. When you insert those objects into the deque, copies are made of type A, "slicing" off the parts that made them B or C originally.
Similarly, A r = B() just creates a temporary B and copies the A part of it into an A called r.
BTW by A a = A(); you might as well write A a;. They're not completely equivalent, but they do the same job here, and you likely meant for the simpler version.
A a;
B b;
C c;
a.taco(); //Class A
b.taco(); //Class B
c.taco(); //Class C
// With pointers and containers
deque<A*> aa;
aa.push_back(&a);
aa.push_back(&b);
aa.push_back(&c);
for (int i=0; i<aa.size(); i++)
aa[i]->taco(); // Hurray!
// With refs
B q;
A& r = q;
r.taco(); // Class B!
(Just remember that those objects a, b and c have automatic storage duration. The moment they go out of scope, if the deque still exists then all its elements are invalid pointers. You may want to employ dynamic allocation to further control the lifetime of the A, B and C objects.. but I'll leave that as an exercise to the reader.)