Different behavior for if-else and ternary operator - c++

I have below class in VS2010-SP1, Ternary operator and if-else seems to be working differently for below code on getname method
template <int size=120> class StringBuf{
public:
StringBuf(const char* src){
strcpy(s,src);
}
// Copy from another StringBuf
StringBuf(const StringBuf& src){
strcpy(s,src.get());
}
// String access
operator const char*() const {return get();}
const char* get() const { return s ; }
private:
char s[size];
};
class MyPony{
StringBuf<10> name;
public:
MyPony(char* name_) : name(name_){}
const char* getname(bool bVal){
//if( bVal )
// return name;
//else
// return "Jimmy";
return (bVal==true) ? name : "Jimmy";
}
};
int main(){
MyPony pony("Pani");
const char* getname = pony.getname(true);
return 0;
}
If I use ternary operator getname() method makes a copy of name by calling copy constructor and then calls operator const char* on the temp copy.
If I change ternary operator into if-else the code just calls operator const char* without making a temp copy.
My understanding is that if else and ternary operator should behave the same, but why is this different behavior for this class? Is there something that I'm overlooking?
For ternary operator VS2005 seems to call operator const char* directly .

Of course: The type of the conditional expression a ? b : c is the common type of b and c, which in your case is StringBuf<10>. So either operand must first get converted to that type before the resulting value can be considered for return.
There conditional expression is an expression, and the if statement is a statement. They're different things for different purposes. Use the if statement in your situation.
You might wonder why the common type is StringBuf<10> and not char const *. That's because of C++11 5.16/3 ("Conditional operator"), which says that implicit conversions are considered. In your case, there is an implicit conversion from char const [6] (the type of "Jimmy") to StringBuf<10>, but not the other way round, so the common type is uniquely defined. For comparison, if you tried x ? name : static_cast<char const *>("Jimmy"), that would not compile.

Related

Understanding char* - C++

I am writing a code in C++ right now, and I have a dilemma.
EDIT: I added the class relevant definition
_fullName is defined in the class as a private dm(char _fullName)
my class contains the getter method below:
char* getFullName() const { return this->_fullName; }
However, I had in the past cases in which I returned char* with const(const char*)
I can change the getter method to this one:
const char* getFullName() const { return this->_fullName; }
Both versions are compiling but I don't know how to choose.
I would take the second version, but I wonder Why even the version without the const is compiling? shouldn't it give an error when I remove the const keyword, because the function is a CONST member function and therefore the dms are const as well and cannot be returned without the const keyword???
This is the class relevant definition:
class Professional
{
private:
char* _ID;
char* _fullName;
int _age;
char* _profession;
}
First understand what const attached to a member function means. It determines the const-ness of the implicit this used for the member. Given this:
struct S
{
char value[10];
const char *mfn() const { return value; }
};
within the confines of mfn the implicit this is const S *. Furthermore, all references to members obtained therein are also const. In this case, that means value as an expression representation is const char (&)[10] before any further conversion are attached therein.
That's important.
In the correct posted example above there is an automatic conversion to temporary pointer, since const char(&)[10] converts to const char* without objection. However, the following will fail:
struct S
{
char value[10];
char *mfn() const { return value; }
};
The reason this will fail is simply because there is no conversion possible. value, remember, is const char (&)[10], and can only implicitly convert to const char*.
But how could it succeed? Well, consider this:
struct S
{
char *ptr;
char *mfn() const { return ptr; }
};
This will work. The reason is subtle, but obvious once you think about it. ptr is a char*. The attachment of const to this makes that char * const&, not const char *& (there is a difference; the former is a reference to a non-mutable pointer to mutable data, the latter is a reference to a mutable pointer to non-mutable data). Since return ptr is not mutating ptr (or anything else in the object), it is viable as a result.
In short, in your case it works because the pointer you are returning isn't via some implicit conversion from a const underlayment; it's just a value.
You have a few things going on here, in your example of the int num member this is not the same as a char * member.
lets expand your example a bit:
class Professional
{
int* func() const
{
return &myInt; // Fails because it returns a reference to a member variable
}
char* func() const
{
return &myChar; // Fails because it returns a reference to a member variable
}
int* func() const
{
return pInt; // ok because it returns a COPY of the member pointer
}
char* func() const
{
return pChar; // ok because it returns a COPY of the member pointer
}
int myInt;
char myChar;
int *pInt;
char *pChar;
Note: the two pointers getting returned by copy are ok. Its the pointers that are copies not the thing being pointed to. The memory that is pointed to is nothing to do with this class.
As to an answer to your question: there is a rule of thumb that is to apply const as much as possible - this helps to show other users your intent and gains benefits from compiler warnings / errors if a user tries to use your class in a way you did not intend. So in this case pass back a const char *.
Note: See this answer for more specific details here: What is the difference between const int*, const int * const, and int const *?

usage of explicit keyword for constructors

I was trying to understand the usage of explicit keyword in c++ and looked at this question on SO
What does the explicit keyword mean in C++?
However, examples listed there (actually both top two answers) are not very clear regarding the usage. For example,
// classes example
#include <iostream>
using namespace std;
class String {
public:
explicit String(int n); // allocate n bytes to the String object
String(const char *p); // initializes object with char *p
};
String::String(int n)
{
cout<<"Entered int section";
}
String::String(const char *p)
{
cout<<"Entered char section";
}
int main () {
String mystring('x');
return 0;
}
Now I have declared String constructor as explicit, but lets say if I dont list it as explicit, if I call the constructor as,
String mystring('x');
OR
String mystring = 'x';
In both cases, I will enter the int section. Until and unless I specify the type of value, it defaults to int. Even if i get more specific with arguments, like declare one as int, other as double, and not use explicit with constructor name and call it this way
String mystring(2.5);
Or this way
String mystring = 2.5;
It will always default to the constructor with double as argument. So, I am having hard time understanding the real usage of explicit. Can you provide me an example where not using explicit will be a real failure?
explicit is intended to prevent implicit conversions. Anytime you use something like String(foo);, that's an explicit conversion, so using explicit won't change whether it succeeds or fails.
Therefore, let's look at a scenario that does involve implicit conversion. Let's start with your String class:
class String {
public:
explicit String(int n); // allocate n bytes to the String object
String(const char *p); // initializes object with char *p
};
Then let's define a function that receives a parameter of type String (could also be String const &, but String will do for the moment):
int f(String);
Your constructors allow implicit conversion from char const *, but only explicit conversion from int. This means if I call:
f("this is a string");
...the compiler will generate the code to construct a String object from the string literal, and then call f with that String object.
If, however, you attempt to call:
f(2);
It will fail, because the String constructor that takes an int parameter has been marked explicit. That means if I want to convert an int to a String, I have to do it explicitly:
f(String(2));
If the String(char const *); constructor were also marked explicit, then you wouldn't be able to call f("this is a string") either--you'd have to use f(String("this is a string"));
Note, however, that explicit only controls implicit conversion from some type foo to the type you defined. It has no effect on implicit conversion from some other type to the type your explicit constructor takes. So, your explicit constructor that takes type int will still take a floating point parameter:
f(String(1.2))
...because that involves an implicit conversion from double to int followed by an explicit conversion from int to String. If you want to prohibit a conversion from double to String, you'd do it by (for example) providing an overloaded constructor that takes a double, but then throws:
String(double) { throw("Conversion from double not allowed"); }
Now the implicit conversion from double to int won't happen--the double will be passed directly to your ctor without conversion.
As to what using explicit accomplishes: the primary point of using explicit is to prevent code from compiling that would otherwise compile. When combined with overloading, implicit conversions can lead to some rather strange selections at times.
It's easier to demonstrate a problem with conversion operators rather than constructors (because you can do it with only one class). For example, let's consider a tiny string class fairly similar to a lot that were written before people understood as much about how problematic implicit conversions can be:
class Foo {
std::string data;
public:
Foo(char const *s) : data(s) { }
Foo operator+(Foo const &other) { return (data + other.data).c_str(); }
operator char const *() { return data.c_str(); }
};
(I've cheated by using std::string to store the data, but the same would be true if I did like they did and stored a char *, and used new to allocate the memory).
Now, this makes things like this work fine:
Foo a("a");
Foo b("b");
std::cout << a + b;
...and, (of course) the result is that it prints out ab. But what happens if the user makes a minor mistake and types - where they intended to type +?
That's where things get ugly--the code still compiles and "works" (for some definition of the word), but prints out nonsense. In a quick test on my machine, I got -24, but don't count on duplicating that particular result.
The problem here stems from allowing implicit conversion from String to char *. When we try to subtract the two String objects, the compiler tries to figure out what we meant. Since it can't subtract them directly, it looks at whether it can convert them to some type that supports subtraction--and sure enough, char const * supports subtraction, so it converts both our String objects to char const *, then subtracts the two pointers.
If we mark that conversion as explicit instead:
explicit operator char const *() { return data.c_str(); }
...the code that tries to subtract two String objects simply won't compile.
The same basic idea can/does apply to explicit constructors, but the code to demonstrate it gets longer because we generally need at least a couple of different classes involved.

overload C++ native variables

I posted a question earlier about how to overload strings, But when I use the same formula for unsigned long long it doesn't work.
I tried a typedef but that didn't work either.
typedef unsigned long long i64;
//a new class to hold extention types, and bytes.
class FileData
{
public:
//conversion operators
operator string(){return extensions_;}
operator i64() {return containsBytes_;}
string& operator= (FileData &);
i64& operator= (FileData &);
string extensions_;
i64 containsBytes_;
};
string &FileData::operator=(FileData& fd)
{
return fd.extensions_;
}
i64 &FileData::operator=(FileData& fd)
{
return fd.containsBytes_;
}
there are two errors in this code.
first one is on line 11:
Error:cannot overload functions distinguished by return types alone
second one is on line 22,
Error:declaration is incompatible with "std::string &FileData::operator=(FileData& fd)"(declared on line 17).
but if I delete any mention of the string conversion it still doesn't work.
I think what you are looking for is these
FileData& operator= (string&);
FileData& operator= (i64&);
FileData& FileData::operator=(string& s)
{
this->extensions_ = s;
return *this;
}
FileData& FileData::operator=(i64& l)
{
this->containsBytes_ = l;
return *this;
}
You are confusing assignment with type conversion operators. Assignment operator is used when you want to assign something to your class. Not to make it compatible with string or long long
With assignment for string overloaded you can do this
FileData a;
string str;
a = str; // This will set a.extensions_ to str, see above.
but not.
str = a;
Because assignment expects your class on the left hand side.
To do str = a; you need to overload conversion operators (). Which you have done.
operator string(){return extensions_;}
With those overloaded
str = a; // This will set str to a.extensions_ See the difference?
First error message
Error:cannot overload functions distinguished by return types alone
These two functions have identical parameters and differ only in return types
string& operator= (FileData &);
i64& operator= (FileData &);
C++ can overload functions only, when they differ in parameters.
Second error message
Error:declaration is incompatible with "std::string &FileData::operator=(FileData& fd)"(declared on line 17).
i64 &FileData::operator=(FileData& fd)
{
return fd.containsBytes_;
}
This is a follow up to the first error. The C++ compiler ignored the second assignment operator, because there was no differing parameters. Now, you define an assignment operator, which is incompatible with the assignment operator declared first above.

Overloading typecasting operators: const & non-const

Why do the following two usecases behave differently?
An example for a built-in type:
class Test
{
operator const char*() {
return "operator const char*() called";
}
operator char*() {
return const_cast<char*> ("operator char*() called");
// a really ugly hack for demonstration purposes
}
};
Test test;
const char *c_ch = test; // -> operator const char*() called
char *ch = test; // -> operator char*() called
Okay, everything works as it should. No, let's try it with a user-defined type:
class ColorWrapper
{
operator const Color() {
cout << "operator const Color() called" << endl;
return Color(10, 20, 30);
}
operator Color() {
cout << "operator Color() called" << endl;
return Color(11, 22, 33);
}
};
ColorWrapper cw;
const Color c_col = cw;
Color col = cw;
The situation looks identical; but now, GCC starts complaining:
error: conversion from 'ColorWrapper' to 'const Color' is ambiguous
error: conversion from 'ColorWrapper' to 'Color' is ambiguous
Am I missing something? What I'm trying to achieve here is to prevent the user from changing the color directly. If they want to change it, they must do it via the wrapper class.
The thing is, that your two examples are not equivalent. The first returns two different types from which the compiler can easily choose, a pointer to mutable data and a pointer to constant data. It would be different, was it a pointer vs a constant pointer (which would mean you cannot change where the returned pointer points, in contrast to not changing the pointed to data):
class Test
{
operator char * const();
operator char *();
};
which would be equivalent to your second example and introduce the same ambiguity, since the compiler cannot decide which one to choose, as both return the same type, one const-qualified and the other not.
This could be solved by overloading based on the constness of the object:
class ColorWrapper
{
operator const Color() const;
operator Color();
};
But this won't buy you anything here, since you return a new object by value anyway, so you can always return the const version, and also the appropriate version would be chosen based on the source object's constness and not the destination obejct's constness (thus call the non-const version in both cases), which doesn't seem what you want.
So you can overload based on the constness of the source object. But you cannot, as you want to now, overload simply based on the constness of the destination object.
This all reduces down to thinking about the difference between an object and the data the object may inderectly refer to, which in practice presents itself as the difference between a constant pointer and a pointer to constant data.
What I'm trying to achieve here is to prevent the user from changing
the color directly
Then there's absolutely no need for any overloading. Just return the const version. The user cannot change the returned color directly, he can only copy it and change the copy.
cw.set(red); //nope, return color is constant
Color col = cw; //copy returned color into col
col.set(green); //fine, since we're not working on the returned color, but on col
const Color c_col = cw; //use this if you don't want c_col to be modified,
//doesn't have anything to do with returned color, though
That is because in your second example you were adding const to a object , not pointer(in your first case). And const with object make compile confuse in overload resolution stage, those two are as good as each other(object vs const object) according to c++ standard. compiler won't be try to smart here and choose one over another.
But in pointer vs const pointer (reference works too), compile can choose from those two overload candiate accordingly,which is your first case.
If you modify one operator to be const, it will work:
operator const Color() const {
cout << "operator const Color() const called" << endl;
return Color(10, 20, 30);
}
Alternatively, you can remove one of the two operators. Since you return the Color by value, there's no real difference between the two operators.
You observe that problem because you basically have 2 different cases here. I think that the easiest way to present what is happening here is to modify a bit your first example:
class Test
{
operator char* const() {
return "operator char* () called";
}
operator char*() {
return const_cast<char*> ("operator char*() called");
// a really ugly hack for demonstration purposes
}
};
Now you have exactly the same situation as in the second example. You basically return a copy (of a pointer) and a const copy and that is why they mess up in overload resolution.
Your original first example works fine because those conversion operators convert to pointers of 2 different types (const char and char). I hope that helps to understand the difference here.
BTW, I personally believe that there is no much sense in returning a const copy from a method. It does not change anything to the user and only obfuscates the class interface.

How do I implicitly specialise conversion?

With the following code, if I attempt to convert a template array to std::string, instead of the compiler using the expected std::string conversion method, it raises an ambiguity resolution problem (as it attempts to call the array conversion methods):
#include <iostream>
template<typename TemplateItem>
class TestA
{
public:
TemplateItem Array[10];
operator const TemplateItem *() const {return Array;}
operator const std::string() const;
};
template<>
TestA<char>::operator const std::string() const
{
std::string Temp("");
return Temp;
}
int main()
{
TestA<char> Test2;
std::string Temp("Empty");
Temp = Test2; //Ambiguity error. std::string or TemplateItem * ?
return 0;
}
What modification do I need to make to the code in order to make it so the code correctly and implicitly resolve to the std::string conversion function? Especially given the const TemplateItem * would be treated as a null-terminated array (which it won't likely be).
First, the reason you have ambiguity: you provide both conversion to char* and conversion to std::string const, and std::string likes them both.
By the way, before getting to your question, the const in operator std::string const was once a good idea, advocated by e.g. Scott Meyers, but is nowadays ungood: it prevents efficient moving.
Anyway, re the question, just avoid implicit conversions. Make those conversions explicit. Now I answered that in response to another SO question, and someone (I believe the person was trolling) commented that C++98 doesn't support explicit type conversion operators. Which was true enough, technically, but pretty stupid as a technical comment. Because you don't need to use the explicit keyword (supported by C++11), and indeed that's not a good way to make the conversions explicit. Instead just name those conversions: use named member functions, not conversion operators.
#include <iostream>
template<typename TemplateItem>
class TestA
{
public:
TemplateItem Array[10];
TemplateItem const* data() const { return Array; }
std::string str() const;
};
template<>
std::string TestA<char>::str() const
{
return "";
}
int main()
{
TestA<char> test2;
std::string temp( "Empty" );
temp = test2.str(); // OK.
temp = test2.data(); // Also OK.
}
Cheers & hth.
I will add, after thinking about it, here's the reasoning and what should be done:
The operator const TemplateItem *(); Should be deleted.
Why? There never will be an instance where you would want implicit conversion of TestA (or any template class) to a TemplateItem array with an unknown size - because this has absolutely no bounds checking (array could be sizeof 1 or 10 or 1000 or 0) and would likely cause a crash if a calling function or class received the array with no idea what size it is.
If the array is needed, either use the operator[] for direct items, or GetArray (which would signal the user intends to pass an unknown-length array).
Retain operator const std::string. Code will compile. Possible memory issues down the line averted.
(Alf for his efforts has been selected as the 'correct' answer, although this is the more logical option)