You've explained what I was after.
However, can you elaborate on the class X wrapper please?
class X is *not* a wrapper.
You are confused.
Why wouldn't I have control over the MyString class without it?
See AString below.
For example, Mike has implied that getVal below is read only.
You could define
std::string& getVal(void) { return s; }
as well but you might want to give it a different name.
I've read elsewhere that
const MyString & GetVal() exposes the member(s) in this case.
#include <string>
class AString: public std::string {
public:
AString(const std::string& s): std::string(s) { }
const
AString& getVal(void) const { return s; }
private:
std::string s;
};
g++ -Wall -ansi -pedantic -c AString.cc
AString.cc: In member function \
`const AString& AString::getVal() const':
AString.cc:6: warning: returning reference to temporary
You probably meant
#include <string>
class AString: public std::string {
public:
AString(const std::string& s): std::string(s) { }
const
std::string& getVal(void) const { return s; }
private:
std::string s;
};
You should *not* return a reference to the private std::string s
unless AString is a container class
because you have no control over the definition of a std::string.
You can't substitute a different data representation for s
because applications which use your AString class
will depend upon s being a std::string.
If you want to return a reference to a private data member,
define a new data type to represent it
and return a reference to an object of that type.
#include <string>
class AString {
public:
class MyString: public std::string {
public:
// constructors
MyString(const std::string& s):
std::string(s) { }
};
private:
// representation
MyString S;
public:
AString(const std::string& s): S(s) { }
const
MyString& getVal(void) const { return S; }
};
Now you can change the representation for AString::MyString
whenever you like without any impact upon application which use it
except that they must be recompiled an relinked
with the latest release of your class library.
whereas returning the underlying data type by value would obviously not
#include <string>
class AString: public std::string {
public:
AString(const std::string& s): std::string(s) { }
AString getVal(void) const { return s; }
private:
std::string s;
};
g++ -Wall -ansi -pedantic -c AString.cpp
Please note that neither example that you gave
initializes std::string s so getVal returns
a reference to an empty string and
an empty string in the respective examples.