Issues with assignment operator and c-strings in C++ - c++

Im making a class that is supposed to be able to assign c-strings the same way the string class i able to:
string a = "My string";
The issue I'm having is that it seams like it is not the operator=( char operand ) that is used for this purpose. So my question is this: What is used instead?
What I have:
class exstring
{
...
public:
exstring& operator=( char* );
...
};
...
int main()
{
exstring test = "test";
}
Which gives:
main.cpp:9:22: error: conversion from ‘const char [19]’ to non-scalar type ‘std::exstring’ requested
Any ideas?

You are not calling your operator = here. You need to learn the difference between assignment and initialization. What you're doing is initialization and you need a constructor that takes the parameter you're providing. In other words:
extring test = "test";
Is exactly the same as:
extring test("test");
Except that in the latter case the constructor could be explicit, but not in the former.

Related

let '=' operator of a certain class run the constructor upon declaration

I want to know if there's a way to make the = operator trigger the constructor (or any method) of a class upon its declaration
let's say
class foo
{
public:
string variable="";
foo(string var)
{
this->variable=var;
}
foo(){}
void operator=(string var)
{
this->variable=var;
}
}
int main()
{
foo obj="new foo object";
}
When I run that, it says "error: conversion from 'const char[15]' to non-scalar type 'foo' requested"
But when I do this
foo obj;
obj="new foo object";
It works
What can I do so the first method will work?
What can I do so the first method will work?
Provide a constructor that takes an argument of type char const *.
And use the initialization list of the constructors to initialize members, not assignments in the constructors body.
BTW:
foo obj = "new foo object";
does NOT call operator=().
Why don't you just use the constructor (that should be declared as explicit anyway, so the construct you want is actually bad practice IIRC)?
Just do:
foo obj("bar");
Also variable should not have a default empty value, the default constructor will create it properly.
You should also put variable in the initializer list.

explicit constructor of the wrong type called

In the following sample, my output is "single param ctor", twice.
My question is twofold, first, why is the bool ctor called rather than the version containing string, and second, is there a way to get the string version called without casting the call?
As an aside, my actual code doesn't call the constructors with hard-coded strings but with something like:
static constexpr auto NONE = "NONE";
Foo aFoo(NONE);
...
#include <iostream>
#include <string>
using namespace std;
struct Foo {
explicit Foo(bool _isVisible = false): id(""), isVisible(_isVisible) {cout << "single param ctor" << endl;}
explicit Foo(const string _id, bool _isVisible = false): id(_id), isVisible(_isVisible) {cout << "multip param ctor" << endl;}
const string id;
bool isVisible;
};
int main(int argc, const char * argv[]) {
shared_ptr<Foo> sharedFoo = make_shared<Foo>("hello");
Foo regFoo("hi");
return 0;
}
This is a limitation of C++ inherited from older C++ and ultimately from C.
Your string literals convert to bool better than to the "user-defined" type std::string.
Instead of casting in the call, you could add a constructor that takes const char*, possibly having it delegate to your existing constructor that takes std::string:
explicit Foo(const char* _id, bool _isVisible = false)
: Foo(std::string(_id), _isVisible)
{};
This constructor will be an "exact match" (or close enough anyway) and prevent bool from stealing the limelight.
Or, since C++14, instead of the cast use the std::string literal, e.g. "hi"s, though you have to remember to do this at the callsite which is a bit "meh" for a general solution.
By the way, if you really want to take your std::string _id parameter by value, don't make it const; you're preventing it from being moved from and necessitating a copy in the member initialiser. Depending on what is going on at your typical callsite, the following may make more sense:
explicit Foo(
string _id,
bool _isVisible = false
)
: id(std::move(_id))
, isVisible(_isVisible)
{}
If you usually pass in an lvalue, though, at least accept a const std::string& to prevent one copy.
why is the bool ctor called rather than the version containing string
Because "hi" is a pointer to char an array of chars that is converted to a pointer to char (thanks, Lightness Races in Orbit), so a number, that i converted to a bool.
there a way to get the string version called without casting the call?
Not really elegant, but... you can pass a second boolean param
Foo regFoo("hi", false);
to exclude the first constructor

inherit from std::string or operator overloading

I want to have a class like below:
Class Test {
Test();
~Test();
...
}
I want to be able to use following statement:
std::string str;
Test t;
str = t;
what should I do? should I override to_string? If yes it seems that it is not possible to inherit from std::string class.
Or I have to override special operator?
What about Pointer assignment? like below:
std::string str;
Test* t = new Test();
str = t;
You can provide a user-defined conversion operator to std::string:
class Test {
//...
public:
operator std::string () const {
return /*something*/;
}
};
This will allow a Test object to be implicitly-converted to a std::string.
Although in C++ it is possible, it is generally not advised to inherit from standard classes, see Why should one not derive from c++ std string class? for more info.
I am wondering, what is the function of the assignment of
str = t;
str is a std::string type, t is Test type. So what is the expected value of the assigment? No one can guess. I suggest to explicitly call a conversion method or an operator for code clarity.
This would make your example look like:
str = t.convertToString();
or the more standard way is to implement the stream operator, which makes
str << t;
(Note this example works if str is a stream type, if it is a string, you need further code, see C++ equivalent of java.toString?.)
But, if you really want it to work without a conversion method, you can override the string assignment operator of Test:
class Test {
public:
operator std::string() const { return "Hi"; }
}
See also toString override in C++
Although this is a perfect solution to your question, it may come with unforeseen problems on the long run, as detailed in the linked article.

overloading operator .

Ok, I know that operator. is not overloadable but I need something like that.
I have a class MyClass that indirectly embeds (has a) a std::string and need to behave exactly like a std::string but unfortunately cannot extend std::string.
Any idea how to achieve that ?
Edit: I want that the lines below to compile fine
MyClass strHello1("Hello word");
std::string strValue = strHello1;
const char* charValue = strHello1.c_str();
As per your later edit, that:
MyClass strHello1("Hello word");
std::string strValue = strHello1;
const charValue = strHello1.c_str();
should compile fine, the only solution is to write a wrapper over std::string:
class MyClass
{
private:
std::string _str;
public:
MyClass(const char*);
//... all other constructors of string
operator std::string& ();
//... all other operators of string
const char* c_str();
//... all other methods of string
friend std::string& operator + ( std::string str, Foo f);
};
//+ operator, you can add 2 strings
std::string& operator + ( std::string str, Foo f);
This however is tedious work and must be tested thoroughly. Best of luck!
You can overload the conversion operator to implicitly convert it to a std::string:
class MyClass
{
std::string m_string;
public:
operator std::string& ()
{
return m_string;
}
};
If you're not interested in polymorphic deletion of a string*, you can derived from std::string, just getting the behavior of your class behaving "as-a" std::string. No more, no less.
The "you cannot derived from classes that don't have a virtual destructor" litany (if that's the reason you say you cannot extend it) it like the "dont use goto", "dont'use do-while" "don't multiple return" "don't use this or that feature".
All good recommendation from and for people that don't know what they are doing.
std::string doesn't have a virtual destructor so don't assign new yourcalss to a std::string*. That's it.
Just make your class not having a virtual destructor itself and leave in peace.
Embedding a string and rewriting all its interface just to avoid inheritance is simply stupid.
Like it is stupid writing dozens of nested if to avoid a multiple return, just as its stupid introduce dozens of state flags to avoid a goto or a break.
There are cases where the commonly considered weird things must be used. That's why those things exist.
You can extend an interface without publically deriving from it. This prevents the case of problematic polymorphic destruction (aka no virtual destructor):
#include <iostream>
#include <string>
using namespace std;
class MyClass
: private std::string
{
public:
MyClass(const char* in)
: std::string(in)
{}
// expose any parts of the interface you need
// as publically accessible
using std::string::c_str;
using std::string::operator+=;
};
int main()
{
MyClass c("Hello World");
cout << c.c_str() << "\n";
c += "!";
cout << c.c_str() << "\n";
// Using private inheritance prevents casting, so
// it's not possible (easily, that is) to get a
// base class pointer
// MyClass* c2 = new MyClass("Doesn't work");
// this next line will give a compile error
// std::string* pstr = static_cast<MyClass*>(c2);
// delete c2;
}
Trying to sum-up all the discussions, it looks like you will never find a suitable dolution because ... your requirements are in cotraddiction.
You want you class to behave as ats::string
std::string behave as a value but
a value does not "change" when accessed but (think to c = a+b: do you expect a and b to change their value ??) ...
when accessing your "value" you want to change it.
If what I summed up collecting all the peaces (suggestion: edit your question otherwise all the answerer will risk to be lost) is correct you are in trouble with 3 & 4 (note the 3. derives from the concept of "assignment", and you can do noting to change it, while 4. comes from you directly)
Now, I can try to reverse-engineer your psychology (because you didn't provide good information about what your class represent and why you cannot "extend" a string) I can find
two possibility neither of which will fit all the above requirements.
Store a string into your class and make your class to behave as a std::string. There are threee ways to come to this point:
a. embed a string and make your class to decay to it:
essentially your class must contain
.
operator std::string&() { return my_string; } //will allow l-value assignments
operator const std::string&() const { return my_string; } //will allow r-value usage
const char* c_str() const { return my_string.c_str(); }
b. derive from std::string. In fact that's like having an anonymous my_string in it, which "decay" operations implicit. Not that different as above.
c. embed or privately derive, and rewrite the std::string interface delegating the std::string functions. It's just a long typing to get exactly the b. result. so what the f..k? (this last question is dedicated to all the ones that believe a. or b. will break encapsulation. c. will break it as well, it will only take longer!)
Don't store a string, but just get it as a result from a calculation (the "lookup" you talk about, not clarifying what it is).
In this last case, what you need is a class that decay automatically into std::string as a value.
So you need, in your class
operator std::string() const { return your_lookup_here; }
note that const is necessary, but there is no need to modify your class inner state, since the resulting string is not stored.
But this last solution has a problem with const char*: since the string is temporary, until you don't assign it, its buffer is temporary as well (will be destroyed) so decaying into const char* to assign the pointer is clueless (the pointer will point to a dead buffer).
You can have a
const char* c_str() const { return std::string(*this).c_str(); } //will call the previous one
but you can use this only into expressions or a pass-through parameter in function calls (since the temporary will exist until the evaluating expression is fully evaluated), not in an assignment towards an l-value (like const char* p; p = myclassinstace.c_str(); )
In all of the above cases (all 1.) you also need:
myclass() {}
myclass(const std::string& s) :my_string(s) { ... }
myclass(const char* s) :my_string(s) { ... }
or - in C++11, just
template<class ...Args>
myclass(Args&&... args) :my_string(std::forward<Args...>(args...)) {}
In case 2., instead of initialize the not existent my_sting, you should use the arguments to set what you will look up (we don't know what it is, since you did not tell us)
Hope in all these option you can find something useful.
You can add an operator const reference to string, as follows:
class C
{
public:
// Implicit conversion to const reference to string (not advised)
operator const std::string &() const
{
return s_;
}
// Explicit conversion to a const reference to string (much better)
const std::string &AsString() const
{
return s_;
}
private:
std::string s_;
};
As you can see from the comments, it would be much better to add an explicit conversion function if you really need this behavior. You can read about why this is bad in the Programming in C++ Rules and Recommendations article.

wrong argument conversion preferred when calling function

I'm writing a program under MS Visual C++ 6.0 (yes, I know it's ancient, no there's nothing I can do to upgrade). I'm seeing some behavior that I think is really weird. I have a class with two constructors defined like this:
class MyClass
{
public:
explicit MyClass(bool bAbsolute = true, bool bLocation = false) : m_bAbsolute(bAbsolute), m_bLocation(bLocation) { ; }
MyClass(const RWCString& strPath, bool bLocation = false);
private:
bool m_bAbsolute;
bool m_bLocation;
};
When I instantiate an instance of this class with this syntax: MyClass("blah"), it calls the first constructor. As you can see, I added the explicit keyword to it in the hopes that it wouldn't do that... no dice. It would appear to prefer the conversion from const char * to bool over the conversion to RWCString, which has a copy constructor which takes a const char *. Why does it do this? I would assume that given two possible choices like this, it would say it's ambiguous. What can I do to prevent it from doing this? If at all possible, I'd like to avoid having to explicitly cast the strPath argument to an RWCString, as it's going to be used with literals a lot and that's a lot of extra typing (plus a really easy mistake to make).
Explicit will not help here as the constructor is not a part of the implicit conversion, just the recipient.
There's no way to control the preferred order of conversions, but you could add a second constructor that took a const char*. E.g:
class MyClass
{
public:
MyClass(bool bAbsolute = true, bool bLocation = false);
MyClass(const RWCString& strPath, bool bLocation = false);
MyClass(const char* strPath, bool bLocation = false);
private:
bool m_bAbsolute;
bool m_bLocation;
};
Andrew Grant provided the solution. I want to tell you why it doesn't work the way you tried. If you have two viable functions for an argument, then the one that matches the argument best is called. The second requires a user-defined conversion, while the first only needs a standard conversion. That is why the compiler prefers the first over the second.
If you don;t want to keep casting it, then it seems to me that you might have to make another ctor that takes a const char*.
That is what I would probably do in this situation.
(Not sure why you are making a ctor with a type that you aren't passing for most of its use.)
edit:
I see someone else already posted this while I was typing mine
Not sure why it should confuse a reference to a string and a bool? I have seen problems with a bool and an int.
Can you lose the default value for the first constructor - it may be that since this is making it the default constructor for MyClass() then it is also the default if it can't match the args
Your choices are to add a constructor that explicitly takes a const char *
MyClass(const char* strPath, bool bLocation = false); // Thanks Andrew Grant!
Or do
MyClass( string("blah") );
The compiler intrinsically knows how to make a const char * into a bool. It would have to go looking to see if, for any of the first-argument types of MyClass constructors, there's a constructor that will take the source type you've given it, or if it can cast it to a type that is accepted by any of the constructors of any of the first-argument types of your MyClass constructors, or... well, you see where this is going and that's only for the first argument. That way lies madness.
The explicit keyword tells the compiler it cannot convert a value of the argument's type into an object of your class implicitly, as in
struct C { explicit C( int i ): m_i(i) {}; int m_i; };
C c = 10;//disallowed
C c( 2.5 ); // allowed
C++ has a set of rules to determine what constructor is to be called in your case - I don't know from the back of my head but you can intuitively see that the default arguments lead towards ambiguity.
You need to think those defaults through.
You can fallback onto some static, named, construction methods. Or you can use a different class (which is not a bad choice from a design viewpoint). In either way, you let the client code decide which constructor to use.
struct C {
static C fromString( const char* s, const bool b = true );
static C fromBools( const bool abs = true, const bool b = true );
};
or
struct CBase {
bool absolute;
bool location;
CBase( bool abs=true, bool loc=true );
};
struct CBaseFromPath {
// makes 'absolute' true if path is absolute
CBaseFromPath( const char* s, const bool loc );
};
Are you certain that it really is calling the first constructor? Are you calling it with the string hard-coded, or is it hidden behind a #define? Are you sure that the #define is what you think it is? (Try compiling with the /Ef option to get the expanded preprocessor output, and see if the call looks like you'd expect it to look.)
EDIT: Based on this and other comments, my suggestion is to add another constructor for const char*. Is that feasible?