Let's say we have the following scenario:
We have a base abstract class A. Then we have classes B and C which derived from A. We also have class D which is a custom implementation of a std::vector<T> - it contains a private property list of type std::vector<T> and some custom methods to work with it.
Now my problem is as follows: I would like to overload the operator + in class A to be able to do this:
B* b = new B();
C* c = new C();
D mList = b+c; //the property *list* of mList would contain b an c
I have tried everything and can't seem to be able to get it to work and am out of ideas. Is it even possible to override an operator in a base abstract class so that it will apply to derived classes?
EDIT:
Here is what I have tried so far:
File A.h:
#pragma once
#include <string>
#include <iostream>
using namespace std;
class A
{
protected:
double price;
string name;
public:
A() :name(""){};
A(string n, double p){
price = p;
name = n;
};
~A(){};
virtual void calculate(double value) = 0;
virtual void print() const = 0;
};
File B.h:
#pragma once
#include "A.h"
class B : public A
{
private:
public:
B() :A(){};
B(string n, double p) :A(n,p){};
~B();
void calculate(double value)
{
price = price + value;
}
void print() const
{
cout << name << " says: " << " " << price;
}
};
File C.h:
#include "A.h"
class C : public A
{
private:
public:
C() :A(){};
C(string n, double p) : A(n,p){};
~C();
void calculate(double value)
{
price = price * value;
}
void print() const
{
cout << name << " says: " << " " << price;
}
};
File D.H:
#include <vector>
class D
{
private:
vector<A*> list;
public:
D(){}
~D()
{
int len = list.size();
for (int i = 0; i < len; i++)
{
delete list[i];
}
};
void push(A* item)
{
list.push_back(item);
}
A* pop()
{
A* last = list.back();
list.pop_back();
return last;
}
//I have tried overriding it here and in A.h
friend D D::operator+(A* first, A* second)
{
D temp;
temp.push(first);
temp.push(second);
return temp;
}
};
It looks like you're are adding two pointers, so A::operator+() won't even be called. But to answer your question, yes, operator overloading is inheritable. Even from an abstract base class.
class A
{
public:
virtual void test() = 0;
int operator+(const A &a) {return 42;}
};
class B : public A
{
void test() {};
};
class C : public A
{
void test() {};
};
int main()
{
B* b = new B();
C* c = new C();
cout << "result: " << *b + *c << endl;
return 0;
}
Output:
result: 42
When c in C* and d is a D* if you write c+d you're just adding pointers, whatever overloads you defined.
Maybe you could redefine pointer addition for A* with a global operator(A*, A*) (not sure it's possible) but it would be quite dangerous for users since it overrides standard behavior.
The better solution is to define operators on references (const) and not pointers, which in your case is a little less convenient since you'd have to write: list = *c + *d;
Also, since you're using containers of pointers for polymorphism, I strongly recommend using shared_ptr.
Working code below (simplified, but with the ability to add more than 2 elements):
#include <list>
using std::list;
struct A {
list<const A*> operator+(const A& right) { // A + A
list<const A*> r;
r.push_back(this);
r.push_back(&right);
return r;
}
list<const A*> operator+(const list<const A*> & right) { // A + list
list<const A*> r = right;
r.push_front(this);
return r;
}
virtual void print() const = 0;
};
list<const A*> operator+(const list<const A*> & left, const A & right) { // list + A
list<const A*> r = left;
r.push_back(&right);
return r;
}
#include <iostream>
struct B : A {
void print() const { std::cout << "B" << std::endl; }
};
struct C : A {
void print() const { std::cout << "C" << std::endl; }
};
int main() {
B b;
C c;
B* pb = new B;
list<const A*> lst = b + c + *pb;
for(list<const A*>::iterator i = lst.begin(); i != lst.end(); ++i) {
(*i)->print();
}
return 0;
}
Take a look at this code-example:
#include <iostream>
class B;
class A;
class A
{
public:
virtual void overrideProp() = 0;
friend int operator+(const B& b, const A& a);
friend std::ostream& operator<<(std::ostream& os, const A& a)
{
return os << a.prop;
}
protected:
int prop;
};
class B : public A
{
public:
B(){overrideProp();}
void overrideProp(){prop=1;}
};
class C : public A
{
public:
C(){overrideProp();}
void overrideProp(){prop=3;}
};
int operator+(const B& b, const A& a)
{
return b.prop + a.prop;
}
class D
{
public:
void operator=(const int& i){d = i;}
friend std::ostream& operator<<(std::ostream& os, const D& a)
{
return os << a.d;
}
private:
int d;
};
int main()
{
B b;
C c;
D d; d = b+c;
std::cout << "B contains: " << b << " C contains: " << c << " D contains: " << d;
}
The output is B contains: 1 C contains: 3 D contains: 4
Here's an compilable and runnable example (http://codepad.org/cQU2VHMp) I wrote before you clarified the question, maybe it helps. The idea is that the addition overload can either be unary (and D defined as a friend), as here, or defined as a non-member binary operator using public methods. Note that I have to dereference the pointers b and c to make this work, as adding pointers often don't make sense.
#include <iostream>
#include <string>
class D {
public:
void Foo() {
std::cout << "D: " << member_ << std::endl;
}
friend class A;
private:
std::string member_;
};
class A {
public:
virtual void Foo() = 0;
A(const std::string &member) : member_(member) {}
D operator+(const A &rhs) {
D out;
out.member_ = member_ + " " + rhs.member_;
return out; // Uses the default copy constructor of D
}
protected:
std::string member_;
};
class B : public A {
public:
B(const std::string &member) : A(member) {}
void Foo() {
std::cout << "B: " << member_ << std::endl;
}
};
class C : public A {
public:
C(const std::string &member) : A(member) {}
void Foo() {
std::cout << "C: " << member_ << std::endl;
}
};
int main() {
B *b = new B("hello");
C *c = new C("world");
b->Foo();
c->Foo();
D d = (*b) + (*c);
d.Foo();
delete b;
delete c;
return 0;
}
The output of this program is:
B: hello
C: world
D: hello world
Related
class Musician {
public: virtual void play() { std::cout << "Play an instrument"; }
};
class Guitarist : public Musician {
public: void play() { std::cout << "Play a guitar"<<endl; }
};
int main(){
Musician armstrong;
Guitarist steve;
Musician* m = &armstrong;
m->play();
m = &steve; //type of (m)=Musician type of (*m) = Guitarist???
}
Why is the type of (*m) = Guitarist? And why if I remove virtual keyword in function of Musician class then type of (*m) = Musician?
class Musician {
public: void play() { std::cout << "Play an instrument"; } //this makes type of(*m) = Musician
};
If I add armstrong = static_cast<Musician>(steve); at the end it donot give error but cause no change (of addr and type) to armstrong. What is the meaning of that line?
Whereas steve = static_cast<Guitarist>(armstrong); gives error :
error: no matching function for call to 'Guitarist::Guitarist(Musician&)'
27 | steve=static_cast<Guitarist>(armstrong);
| ^
Have tried to do this before while I was learning here's I had come with a solution you can replace A with Musician and B with Guitarist.
#include <iostream>
class A {
public:
void Same(){
std::cout << "From A" << std::endl;
}
virtual A& operator= (const A& a) {
assign(a);
return *this;
}
protected:
void assign(const A& a) {
}
};
class B : public A {
public:
void Same(){
std::cout << "From B" << std::endl;
}
virtual B& operator= (const A& a) {
if (const B* b = dynamic_cast<const B*>(&a))
assign(*b);
return *this;
}
protected:
void assign(const B& b) {
A::assign(b);
}
};
int main(){
A a;
B b;
a.Same();
a = b;
a.Same();
return 0;
}
I am working with conversion operators and I an error just popped out of nowhere. C class is derived from B and has no relation with class A, however, debugger shows that when doing C* val1 = new C val1 is showed as C* {A<B>}. It also produces an error because that A in the C* pointer has a size of an unreasonable size (it gives a different size each time it is executed so I just suppose it gets a number from another application).
#include <iostream>
#include <vector>
template<typename widget_type>
class A
{
public:
std::vector<widget_type*> value;
virtual ~A() {}
void Add(widget_type* val)
{
value.push_back(val);
}
template<typename return_type>
operator A<return_type>()
{
unsigned int size = this->value.size();
std::vector<return_type*> return_value;
return_value.reserve(size);
for (unsigned int i = 0; i < size; i++)
{
return_value[i] = dynamic_cast<return_type*>(this->value[i]);
}
A<return_type> target;
target.value = return_value;
return target;
}
};
class B
{
public:
virtual ~B() {}
};
class C : public B
{
public:
void Print()
{
std::cout << "C CALL\n";
}
};
class D : public B
{
};
int main()
{
std::cout << "Start!\n";
A<C> source;
C* val1 = new C;
source.Add(val1);
A<B> target = source;
A<B>* target2 = dynamic_cast<A<B>*>(&source);
std::cout << "END\n";
}```
for (unsigned int i = 0; i < size; i++)
{
return_value[i] = dynamic_cast<return_type*>(this->value[i]);
}
You are invoking undefined behaviour by accessing return_value[i] on an empty vector.
I have a problem with my code. I have two classes, A and B, and B inherits A. I also have operators << overloaded in both classes.
Everything works, I have no compiler errors, but it seems something is wrong. As far as I understand polymorphism, when I use pointers to base class while creating child class with new, calling a method should match the child class, not the base class.
For the code below,
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
A(int aa) : a(aa) {};
virtual void show(ostream& o) const
{
o << "a = " << a << "\n";
}
};
ostream& operator << (ostream& os, const A &o)
{
o.show(os);
return os;
}
class B : public A
{
private:
int b;
public:
B(int bb, int aa) : A(aa), b(bb){}
int getb() const {return b;}
};
ostream & operator << ( ostream & os, const B & o)
{
os << static_cast <const A &>(o);
os << "\n";
os << "b = " << o.getb() << "\n";
return os;
}
int main()
{
A *o1 = new B(2,3);
cout << *o1;
cout << "---------------------\n";
B *o2 = new B(2,3);
cout << *o2;
return 0;
}
In main:
A *o1 = new B(2,3);
cout << *o1;
Shows a = 3, instead of showing a = 3 b = 2 (the call should match the child class, not the base class). The thing is, I need to implement the << and >> operators in every child class, but I think they do not behave as they should.
The output of the program:
Even the modified code with re-implmented show method shows wrong results, it does not show a at all this time:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
A(int aa) : a(aa) {};
virtual void show(ostream& o) const
{
o << "a = " << a << "\n";
}
};
ostream& operator << (ostream& os, const A &o)
{
o.show(os);
return os;
}
class B : public A
{
private:
int b;
public:
B(int bb, int aa) : A(aa), b(bb) {}
int getb() const
{
return b;
}
void show(ostream& o) const
{
o << "b = " << b << "\n";
}
};
ostream & operator << ( ostream & os, const B & o)
{
os << static_cast <const A &>(o);
o.show(os);
return os;
}
int main()
{
A *o1 = new B(2,3);
cout << *o1;
cout << "---------------------\n";
B *o2 = new B(2,3);
cout << *o2;
return 0;
}
enter image description here
you have to implement the virtual function show in derived class B:
class B: public A
{
public:
// some code here
virtual void show(ostream& o) const
{
o << "b = " << b << "\n";
}
};
when I use pointers to base class while creating child class with new,
calling a method should match the child class, not the base class
It does when you call a member function ("method" in some other languages), but operator<< is not a member function – it's an overloaded free function.
When choosing an overload, only the types known at compile-time are used.
Since o1 is an A*, *o1 is an A&, and the overload for A& is chosen.
You're doing this a bit "backwards"; you only need one operator<<, for the base class, which calls the virtual show, and then you override show in the derived classes.
Like this:
class A
{
// ...
virtual void show(ostream& o) const
{
o << "a = " << a << "\n";
}
};
ostream& operator << (ostream& os, const A &o)
{
o.show(os);
return os;
}
class B : public A
{
// ...
void show(ostream& o) const override
{
A::show(o); // Do the "A part".
o << "b = " << b << "\n";
}
};
Follow the same pattern for operator>>.
Is there any way in C++ to collect different types of classes and call their methods?
What I want to do is as below,
template<namespace T>
class A
{
A method_A1(T a)
{
...
}
void method_A2(int aa)
{
...
}
...
};
class B
{
...
};
class C
{
...
};
class D
{
...
};
A<B> *b;
A<C> *c;
A<D> *d;
b -> method_A2(3);
c -> method_A2(5);
In this code object b,c,d they are totally different object, right? Not related.
But I want to bind them with a array, so...
z[0] = b;
z[1] = c;
z[2] = d;
like this.
I found some solutions, however the solutions are only for collecting different types. (using void* arrays or vectors for inherited objects) I also wanna access to their methods.
z[0] -> method_A2(3);
z[1] -> method_A3(5);
like this.
In this case how should I do?
Thanks in advance.
typedef boost::variant<A<B>, A<C>, A<D>> AVariant;
std::array<AVariant, 3> z;
z[0] = *b;
z[1] = *c;
z[2] = *d;
Then you can inspect each element's type if needed, or "visit" them using boost::static_visitor as shown here: http://www.boost.org/doc/libs/release/doc/html/variant.html
Why you don't use inheritance and polymorphisms. I have posted an example of what exactly can be a solution of your problem. See the main function:
#include <iostream>
class weapon {
public:
int fireRate;
int bulletDamage;
int range;
int activeBullet;
public:
virtual void fire(void) {std::cout << "machine " << '\n';}
virtual ~weapon() {std::cout << "destructor is virtual" << '\n';}
};
class machineGun: public weapon {
public:
void fire(void) {std::cout << "machine gun firing" << '\n';}
~machineGun(void) { std::cout << "machine gun destroyed" << '\n';}
};
class flamer: public weapon {
public:
void fire(void) {std::cout << "flamer firing" << '\n';}
~flamer(void) {std::cout << "flamer destroyed" << '\n';}
};
int main(void)
{
const int count = 2;
weapon *weapons[count];
machineGun *a = new machineGun();
flamer *b = new flamer();
weapons[0] = a;
weapons[1] = b;
weapons[0]->fire();
weapons[1]->fire();
delete a;
delete b;
}
If you don't want to change your classes' hierarchy, you can try having an array of callable objects. Something like:
#include <iostream>
#include <functional>
#include <array>
class A
{
public:
void Foo(int a)
{
std::cout << "Foo " << a << std::endl;
}
};
class B
{
public:
void Bar(int a)
{
std::cout << "Bar " << a << std::endl;
}
};
int main()
{
using namespace std::placeholders;
A a;
B b;
auto a_func = std::bind(&A::Foo, a, _1);
auto b_func = std::bind(&B::Bar, b, _1);
std::array<std::function<void(int)>, 2> arr = {
std::bind(&A::Foo, a, _1),
std::bind(&B::Bar, b, _1)
};
arr[0](1);
arr[1](2);
return 0;
}
BTW, this will only work if you use compiler with full C++11 support.
I am learning about friends in classes and my problem is:
I want funcC3() to set and permanently change C1::a value, how to do it?
I want global function gfunc() to be able to do the same, how?
Could you please provide me the way i do it, because in the book they don't specify?
#include <iostream>
using namespace std;
class C2;
class C3
{
public:
void funcC3(int const& x)
{
cout << "in third class...: " << x << endl;
};
};
class C1
{
private:
int a;
public:
void funcC1()
{
cout << "inside C1 private thingie: " << a << endl;
};
int C1::getcha();
friend class C2;
friend int gfunc(int chair);
friend void C3::funcC3(int const& a);
};
int C1::getcha()
{
return a;
};
class C2
{
public:
int a;
};
**int gfunc(int ch)**
{
int chair = ch;
return chair;
};
**int main()**
{
C1 obj1;
C3 obj3;
obj3.funcC3(10);
obj1.funcC1();
gfunc(12);
cout << C1.geta() << endl;
system("pause");
}
I want funcC3() to set and permanently change C1::a value, how to do
it?
Declare it as friend function in C1:
class C1; //forward declaration
class C3
{
//...
void funcC3( C1& c);
};
class C1
{
//...
private:
int a;
friend void C3::funcC3( C1&);
};
void C3::funcC3( C1& c) { c.a = 100;}
I want global function gfunc() to be able to do the same, how?
Same as above:
class C1;
void gfunc( C1& c);
class C1 {
//...
private:
int a;
friend void gfunc( C1& c);
};
void gfunc( C1& c) { c.a = 100;}