Dr-Shadow
Dr-Shadow

Reputation: 23

Cpp Operator = between 2 classes

I have a surprising issue in VS2010.

This is the header.h of my main.cpp

class A;
class B;

class A
{
public:
    double x,y;
    A();
    ~A();
    A(const A &obj);
    A(const B &obj);
    A& operator=(const A &obj);
};

class B
{
public:
    double x,y;
    B();
    ~B();
    B(const B &obj);
    B& operator=(const B &obj);
};

The main.cpp is containing the declaration of methods and :

#include "header.h"
#include <iostream>

int main() {
    A t;
    B u;
    A a(u);
    t=u;
    return 0;
}

As you can see, to do

A a(u);

I had to add this method

A(const B &obj);

But for

t=u;

It uses

A& operator=(const A &obj);

Why I don't get an error ?

Upvotes: 0

Views: 82

Answers (3)

Martin J.
Martin J.

Reputation: 5118

If you want to avoid this, you should mark your "A from B" constructor as explicit:

explicit A(const B &obj);

Any constructor not marked as explicit will be used by the compiler for implicit conversions.

Upvotes: 2

jlouzado
jlouzado

Reputation: 502

If, for whatever reason, the A(const B &obj) is meaninful but you also want t=u to fail then you have to disable implicit type conversion using the explicit keyword.

This means that only when you specifically cast B as an instance of A will the conversion be performed.

Upvotes: 0

stefaanv
stefaanv

Reputation: 14392

by adding A(const B &obj); you provided a way to convert B to A, which is used in t=u; so the compiler can do what you ask and no error is needed. The conversion can be done because the parameter const A &obj allows conversion.

Upvotes: 0

Related Questions