mi*************@yahoo.com wrote:
Are there any issues with returning a const reference value
for public "get" accessor methods?
eg.
const std::string& getVal(void) const; // or
const MyString& getVal(void) const;
cat X.h
#ifndef GUARD_X_H
#define GUARD_X_H 1
#include <string>
class X {
public:
class MyString: public std::string {
public:
// constructors
MyString(const std::string& s):
std::string(s) { }
};
private:
// representation
MyString S;
public:
// functions
const
MyString& getVal(void) const { return S; }
// constructors
X(const MyString& s): S(s) { }
};
#endif//GUARD_X_H 1
cat main.cc
#include <X.h>
#include <iostream>
int main(int argc, char* argv[]) {
X x(std::string("Michael Katsilis"));
std::cout << x.getVal() << std::endl;
return 0;
}
g++ -I. -Wall -ansi -pedantic -o main main.cc
./main
Michael Katsilis
Assuming that X is *not* a container class
for objects of type std::string,
you (the class library developer)
*must* retain control over the definition of class MyString.
I have nested the definition of class MyString
inside the definition of class X to emphasize this point.
I have made std::string a *public* base class for MyString.
This means, in general, that MyString *must* provide
every method provided by std::string.
You probably won't want to do that.
You should probably make whatever representation
you want for MyString private and provide *only*
the methods that MyString should have.
That way, you should be able to substitute
any representation for MyString that you want
at a later date without breaking any code that uses class X.