jamby
jamby

Reputation: 606

Pointer conversion, cannot convert Two* to One*

Say I have two classes, One and Two. One and Two are essentially the same, but Two can convert into One.

#ifndef _ONE_H_
#define _ONE_H_

class One
{
private:
    float m_x;
    float m_y;

public:
    One();
    One(float x, float y);
};

#endif
#ifndef _TWO_H_
#define _TWO_H_

#include "One.h"

class Two
{
private:
    float m_x;
    float m_y;

public:
    Two();
    Two(float x, float y);
    operator One() { return One(m_x, m_y); }
    operator One* () { return &One(m_x, m_y); }
    operator One& () const { return *this; }

    float GetX(void) { return m_x ;}
    float GetY(void) { return m_y ;}

    void Print();
};

#endif

Two has access to One, but One does not have access to Two. In the main.cpp I have:

One a(4.5f, 5.5f);

Two b(10.5, 7.5);

One * c = &b;

I get an error if I try to do the pointer of a One to the address of a Two. The error is "error C2440: 'initializing' : cannot convert from 'Two *' to 'One *'"

I cannot for the life of me figure out how to do this, if it is even possible. Any help would be appreciated.

EDIT: Added a new line to Two.h with operator One& () const { return *this; }. The function I'm attempting to use to get this conversion operator to work is void TestRefConstPrint(const One &testClass); With main below, this presents a new error for "cannot convert parameter 1 from Two' to 'const One &'.

Inside main I do:

int main()
{
    Two b(10.5, 7.5);

    TestRefConstPrint(b);

    return 0;
}

Upvotes: 0

Views: 1804

Answers (1)

HighCommander4
HighCommander4

Reputation: 52759

Your conversion operators enable the conversions Two -> One and Two -> One*. You are trying to perform a different conversion, Two* -> One*.

To use your operator One() conversion operator to perform a Two -> One conversion, just do this:

One c = b;

If you really want to do a Two* -> One* conversion, you can, with an explicit cast:

One * c = (One *)&b;

or using C++-style casts:

One * c = reinterpret_cast<One *>(&b);

Note, however, that this does not use either of your conversion operators, and does a very different thing from the Two -> One conversion: it does not create a new object, it makes a pointer-to-One that points to the memory occupied by a Two object. This is generally a bad idea, and it's unlikely that you want to do this.


Finally, a comment about your operator One*(): it returns a dangling pointer (a pointer to a local variable which goes out of scope when the function returns). I assume you wrote it in your attempt to get the Two* -> One* conversion to work. You should remove it because it does not do what you want.

Upvotes: 1

Related Questions