Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading assignment operator for pointers to two different classes

My Question: I'm trying to overload the assignment operator for pointers to two different classes. Here is an example:

dc.h:

#ifndef DC_H_
#define DC_H_

#include "ic.h"

class dc {

double d;
char c;

public:

dc(): d(0), c(0) { }

dc(double d_, char c_): d(d_), c(c_) { }

dc* operator=(const ic* rhs);

~dc() { }

};

#endif /* DC_H_ */

class ic.h:

#ifndef IC_H_
#define IC_H_

class ic {

int i;
char c;

public:

ic(): i(0), c(0) { }

ic(int i_, char c_): i(i_), c(c_) { }

~ic() { }

};

#endif /* IC_H_ */

dc.cpp:

#include "dc.h"

dc* dc::operator=(const ic* rhs) {
d = rhs->i;
c = rhs->c;  
return this;
}

ic.cpp:

#include "ic.h"

main.cpp:

#include "dc.h"
#include "ic.h"

#include<iostream>

int main() {

dc DC;
ic IC;

dc* dcptr = &DC;
ic* icptr = &IC;

dcptr = icptr;

return 0;
}

I get the following error message:

error: cannot convert 'ic*' to 'dc*' in assignment

All this works if I do it with references instead of pointers. Unfortunately since I would like to use pointers to ic and dc as members in another class I cannot use references since references as members have to be initialized and once initialized they cannot be changed to refer to another object. I'd like to be able to make arithmetic operations with ic and dc e.g.:

dc *d1, *d2, *d3;
ic *i1, *i2, *i3;
*d1 = (*d1)*(*i1) + (*i2)*(*d2) - (*d3)*(*i3);

However I want my code to look nice and don't want to have (*)*(*) all over the place. Instead something like this:

d1 = d1*i1 + i2*d2 - d3*i3;

This is the reason why I'd like to do this. Please let me know if this is possible at all. To me it seems that the compiler wants to call the default pointer to pointer assignment instead of the overloaded one.

Thanks for your help in advance!

like image 711
gomfy Avatar asked May 28 '26 23:05

gomfy


1 Answers

You cannot overload operators for pointers.

One option, if you want to stick with operator overloading is to make a pointer wrapper object, an object that contains a pointer to the object - essentially a smart pointer, and overload the operators of that object.

like image 63
Karthik T Avatar answered May 30 '26 14:05

Karthik T