-1

I am trying to learn how to use the keyword const while making header and class files (using OOP). Aka learning the correct way to incorporate the keyword 'const' while making and calling the functions.

// Example.h
        class Example {
            public:
                string getName() const;
                void setName(const string aName);
            private:
                const string name;
        };


// Example.cpp
        #include "Example.h"
        #include <string>;
        #include <iostream>;

        Example::Example();

        string Example::getName() const{
            return name;

    // the following setter does not work
        void Example::setName(const string aName){
            name = aName;
    }

I figured out how to declare variable and getter/setter functions, using const in the header file. Just need help in using const with setter function in class file.

satjav
  • 31
  • 4
  • 1
    Think it through. If the member of the class is `const`, should yo be able to change it with `setName`? – NathanOliver Jan 18 '19 at 19:41
  • _@satjav_ What did you miss at your [research efforts](https://www.google.com/search?q=c%2B%2B+when+to+use+const&oq=c%2B%2B+when+to+use+const&aqs=chrome..69i57j0l5.12084j0j8&sourceid=chrome&ie=UTF-8). Can you elaorate a bit more please? – πάντα ῥεῖ Jan 18 '19 at 19:43
  • I just realized my mistake. Thanks to @Jesper Juhl, – satjav Jan 18 '19 at 19:47

1 Answers1

1
// the following setter does not work
    void Example::setName(const string aName){
        name = aName;" 

Of course it doesn't. You declared name to be const so you cannot assign to it (you can only initialize it). Remove const from name and your setter will work.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70