Consider the code I wrote below:
#include <iostream>
using namespace std;
class Sample{
int a;
public:
Sample(){a=0;cout << "Sample Created (Default Constructor)" << endl;}
Sample(int n):a(n){cout << "Sample Created" << endl;}
~Sample(){ cout << "Sample destroyed" << endl;}
Sample(Sample& s){a=s.getA(); cout << "Sample Copy Constructor called" << endl;}
Sample& operator= (Sample& s){this->a=s.getA(); cout << "Assignment Operator Called" << endl;return (*this);}
void setA(int n){ a=n;}
int getA(){return a;}
};
class Test{
Sample k;
public:
Test(){ cout << "Test Created(Default Constructor)" << endl;}
Test(Sample& S):k(S){ cout << "Test Created" << endl;}
~Test(){cout << "Test Destroyed" << endl;}
Test& operator= (Test& test){ k = test.getK(); cout << "Test Assignement Operator called" << endl; return (*this); }
Test(Test& test){k=test.getK();cout << "Test Copy Constructor called" << endl;}
Sample getK(){return k;}
void setK(Sample& s){k=s;}
};
int main()
{
Sample a1(5);
Test b1(a1);
Test b2=b1;
return 0;
}
In the compilation process, I get the following errors:
$ g++ -Wall Interview.cpp -o Interview
Interview.cpp: In member function `Test& Test::operator=(Test&)':
Interview.cpp:23: error: no match for 'operator=' in '((Test*)this)->Test::k = Test::getK()()'
Interview.cpp:12: note: candidates are: Sample& Sample::operator=(Sample&)
Interview.cpp: In copy constructor `Test::Test(Test&)':
Interview.cpp:24: error: no match for 'operator=' in '((Test*)this)->Test::k = Test::getK()()'
Interview.cpp:12: note: candidates are: Sample& Sample::operator=(Sample&)
When I make changes to here 2as - Sample& getK(){return k;}, it compiles fine.
Can someone explain why this is so?
Also in here 1, if the function is defined asTest& operator= (const Test& test){ k = test.getK(); cout << "Test Assignement Operator called" << endl; return (*this); }
I get an error -
$ g++ -Wall Interview.cpp -o Interview
Interview.cpp: In member function `Test& Test::operator=(const Test&)':
Interview.cpp:23: error: passing `const Test' as `this' argument of `Sample& Test::getK()' discards qualifiers
Why is that?
source
share