Search code examples
c++classreturn-valuedynamic-memory-allocationgetter-setter

C++: How does a getter return a pointer to a dynamically allocated array without giving direct acces to it?


So the question is:

If I have a program something like:

class Ticket
{
 private: 
    char* concertName;
 public:
    Ticket(char* name="Concert");
    char* getConcertName();
}
int main()
{
   char* test;
   Ticket t1;
   test=t1.getConcertName();
   test[1]='A';     
}
Ticket::Ticket(char* name)
{
   this->concertName=new char[strlen(Concert)+1];
   strcpy(this->concertName,name);
}
Ticket::getConcertName()
{
  return this->concertName;
}

What would the getter return? My intuition says that it returns the pointer to the first element of the memory block that I allocated earlier for concertName, and so I can change the array's values without using the setter, directly from main like I did in the example.

It works to change it, but the idea of the private area is for restricting the access from outside the object to it's attributes if a setter or a getter isn't used.

What if we had a static field like: static unsigned int* arrayI; and a static method that worked like a getter returning the value from arrayI?


Solution

  • I think you're asking for const:

    Adding const to your getter will prevent the caller to modify the pointee.

    #include <cstdio>
    class Ticket
    {
     private:
        char concertName[sizeof("Concert")];
     public:
        Ticket(const char *name = "Concert");
        const char* getConcertName() const;
    };
    
    int main()
    {
       const char *test;
       Ticket t1;
       test = t1.getConcertName(); //OK with const
       //test[1]='A'; // would not compile
    }
    Ticket::Ticket(const char *name)
    {
       snprintf(concertName, sizeof(concertName), "%s", name);
    }
    const char *Ticket::getConcertName() const
    {
      return concertName;
    }