0
#include <iostream>
#include <string.h> // strlen, strcpy

Here we have the Base class with a non-default ctor, a getter for name and its destructor.

class Base {
  char *name_;
public:
  Base(const char* str)
    : name_{new char[strlen(str)]}
  {
    strcpy(name_,str);
  }
  char * name() const
  {
    return name_;
  }
  virtual ~Base()
  {
    delete [] name_;
  }
};

Derived class inherits from Base publicly and has its own non-default ctor.

class Derived : public Base {
public:
  Derived(const char* str)
    : Base(str){}
};

My question is how do I make the last line of code in main to work?

int main()
{
  char d1name[] {"d1"};
  Derived d1(d1name);
  std::cout << d1.name() << std::endl;

  d1.name[0] = 'D';
}
shinichi
  • 33
  • 7
  • 1
    You seem to have forgotten that the real name of strings is ***null terminated*** byte strings. That null terminator is not counted by `strlen`. Why don't you make it easy for yourself and use `std::string`? – Some programmer dude Jun 25 '17 at 11:17
  • As for your question, you make it work either by doing e.g. `d1.name()[0]`, or by [reading more about operator overloading](http://en.cppreference.com/w/cpp/language/operators). Perhaps you should [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) which should explain it all. – Some programmer dude Jun 25 '17 at 11:19
  • Possible duplicate of [Operator overloading](https://stackoverflow.com/questions/4421706/operator-overloading) – Richard Critten Jun 25 '17 at 11:20
  • @Someprogrammerdude Right I forgotten about the null character at the end. It's a quiz that was set by my prof. He just wanted it to be that way. – shinichi Jun 25 '17 at 11:28

1 Answers1

0

My question is how do I make the last line of code in main to work?

Just add parenthesis to call the getter

    d1.name()[0] = 'D';
        // ^^

But in general that's a not so good idea. You could make the char array in your base class public then, or even better use a std::string at all.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190