Overloading assignment operator

Greetings. I am trying to overload an assignment operator for an object so that a statement such as "X = 5;" is legal. However, the code won't compile. I am especially stumped as to why the compiler complains about the main program but not the include file with the class. Thanks for your help.

Using the g++ compiler I get the following error

b.cpp: In function `int main()':
b.cpp:11: error: conversion from `int' to non-scalar type `throwaway_class' requested

when I try to compile the following code:

File b.cpp
----------

#include <iostream>

using namespace std;

#include "throwaway_class.h"

int main()
{
throwaway_class var1(5.0, 'c');
throwaway_class var2 = var1;
throwaway_class var3 = 6;

cout << var1.GetField1() << " " << var1.GetField2() << endl;
cout << var2.GetField1() << " " << var2.GetField2() << endl;
cout << var3.GetField1() << " " << var3.GetField2() << endl;
}


File throwaway_class.h
----------------------

class throwaway_class
{
public:

throwaway_class(float Field1_x, char Field2_x);

float GetField1();
char GetField2();

throwaway_class& operator=(const throwaway_class& xxx);
throwaway_class& operator=(int i);

private:
float Field1;
char Field2;
};

//----------------------------------------------------------------------

float throwaway_class::GetField1(){return Field1;}

char throwaway_class::GetField2(){return Field2;}

throwaway_class::throwaway_class(float Field1_x, char Field2_x)
{Field1=Field1_x; Field2=Field2_x;}

//----------------------------------------------------------------------
//
// Overloaded = operator.
//

throwaway_class& throwaway_class::operator=(int i)
{
Field1 = i;
Field2 = 'r';
return *this;
}

//----------------------------------------------------------------------
//
// Overloaded = operator.
//

throwaway_class& throwaway_class::operator=(const throwaway_class& xxx)
{
if (this == &xxx)
return *this;

Field1 = xxx.Field1;
Field2 = xxx.Field2;

return *this;
}




That is because you are getting confused between initialisation and assignment.
You might need to change int i to int& i (although I'm not 100% sure).
It is happening because the line:

 
throwaway_class var3 = 6;


is actually trying to call the following constructor (EDIT: which you have not declared/written):

 
throwaway_class( int );


not the assignment operator, even though your line of code has an equals sign in it.

To test your code, you need to break it into two lines:

1
2
throwaway_class var3;   // Will require a default constructor that you have not provided
var3 = 6;  // Will now call throwaway_class::operator=( int ) 


Last edited on
Topic archived. No new replies allowed.