Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a class that can initialize C++ data types?

The title basically says it all. I mainly want to do this so that I can create an object (say, a custom string object) that can initialize the parameters of other functions in other APIs. Here's an example of me trying to get a custom integer class to work:

#include <iostream>
using namespace std;

class test
{
public:
    int member;
    test(int i) : member(i) {}

    friend int &operator=(int &i, test t);
};

int &operator=(int &i, test t)
{
   return (i = t.member);
}

int main()
{
    int i;
    test t = 90;

    cout << (i = t);
    return 0;
}

Unfortunately I receive an error saying that operator= needs to be a member function. I understand the C++ standard's goal in preventing static and non-member overloads for the assignment operator from being implemented, but is there any other way to do this? Thanks for any help/suggestions!

like image 885
AutoBotAM Avatar asked Feb 05 '26 06:02

AutoBotAM


2 Answers

This is not done with an assignment operator but with an overloaded typecast. This would make your main function work like expected:

#include <iostream>
using namespace std;

class test
{
public:
    int member;
    test(int i) : member(i) {}
    operator int() const {return member;}
};

int main()
{
    int i;
    test t = 90;

    cout << (i = t);
    return 0;
}
like image 64
manol Avatar answered Feb 06 '26 20:02

manol


What you are trying to do needs an conversion operator

operator int() 
{
    return this->member;
}

For the class you are trying to write(containing only integer members), You do not need to overload the = operator.

= operator is one of the member functions that is generated by the compiler by default for every class. Caveat is, it does a simple bit by bit copy(shallow copy) of class members, since you have only integers it should be good enough for you.

You would need to overload the = operator if you had dynamically allocated pointers as member functions, because in that case a shallow copy of those pointers would result in all the objects containing a member pointer pointing to the same dynamic memory location & if one of the object finishes it lifetime, other objects are left with a dangling pointer.
As @Tony, aptly points in out comments Shallow copy is usually bad but not always. See his comments for a scenario.

If at all you want to overload the assignment operator check out the Copy and Swap Idiom to do it right way.

You should also check out the Rule of Three.

like image 24
Alok Save Avatar answered Feb 06 '26 18:02

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!