string a = "Hello";
That will not work in C++11 and later, because you have declared string
as a typedef
for a non-const char*
pointer, but the string literal "Hello"
is a const char[6]
that decays into a const char*
pointer. You can't assign a const char*
to a non-const char*
.
However, prior to C++11, you could assign a string literal to a non-const char*
pointer, but that practice was discouraged as it promoted the possibility of modifying read-only data. Which is why it is no longer allowed in C++11 and later.
You likely meant to use your String
class instead:
String a = "Hello";
But that will not work either, because your String
class lacks a constructor that accepts a const char*
as input.
int i = a.length();
int i = a.length;
Neither of those will work, because a
is declared as a char*
pointer, so it has no methods or data members. But, even if you had used your String
class instead, a.length()
would still not work because length()
is implicitly private
and it takes a char*
as input, which you are not passing in.
typedef char *string;
class String { //same name of typedef and class means compilation error
They don't have the same name. C++ is case-sensitive, so string
and String
are different names.
But using that implementation it would have to be used like:
String a = new String;
a.value = "Hello World";
Wrong. If implemented properly, it can be used like this:
String a = "Hello World";
In order for that to work, your String
class would need to look more like this:
class String {
private:
char *value;
public:
String(const char* str);
~String();
int length() const;
};
And then you can implement it like this:
#include <cstring>
String::String(const char* str)
: value(NULL)
{
if (str) {
value = new char[std::strlen(str) + 1];
std::strcpy(value, str);
}
}
String::~String()
{
delete[] value;
}
int String::length() const
{
return (value) ? std::strlen(value) : 0;
}
Now this will work, as expected:
String a = "Hello";
int i = a.length();
Demo
Obviously, this is just an example, there are better ways to implement this. Like caching the length value in a data member. And implementing a copy constructor and a copy assignment operator, and a move constructor and a move assignment operator, per the Rule of 3/5/0.
Now, that being said, C++ already has a standard std::string
class that handles all of these details for you. Implementing a custom String
class is fine as an exercise in learning how to implement classes, but in real production code, use std::string
instead, eg:
#include <string>
std::string a = "Hello";
size_t i = a.length(); // or a.size()