Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
Hi,

I just learnt about pointers and const and now I'm moving to topic Classes. So I still have a bit of confusion on pointers applied in the codes from Listing 9.7 here.

C++
#include <iostream>

using namespace std;

class MyString
{
private:
    char * Buffer;

public:
    //Constructor
    MyString(const char * InitialInput)
    {
        if(InitialInput != NULL)
        {
            Buffer = new char[strlen(InitialInput)+1];
            strcpy(Buffer, InitialInput);
        }
        else
            Buffer = NULL;
    }
    //Destructor
    ~MyString()
    {
        cout << "Invoking destructor, clearing up\n";
        if (Buffer != NULL)
            delete [] NULL;
    }

    int GetLength()
    {
        return strlen(Buffer);
    }

    const char * GetString()
    {
        return Buffer;
    }
};

int main()
{
    MyString SayHello("Hello from String Class");
    cout << "String buffer in MyString is " << SayHello.GetLength();
    cout << " characters long\n";
    
    cout << "Buffer contains: " << SayHello.GetString() << endl;
    
    return 0;
}


I understand that Buffer is a pointer and in constructor Buffer is assigned the address of dynamic memory of whatever typed in InitialInput.

What I would like to know here is in constructor, for string copying, why is it written like this
C++
strcpy(Buffer, InitialInput);


why not like this?
C++
strcpy(*Buffer, InitialInput);


And another question is, what does it mean with the const and asterisk in this method.
C#
const char * GetString()
{
    return Buffer;
}


I hope anyone who knows can explain this to me. Thanks for taking the time reading and answering my questions.
Posted
Comments
Stefan_Lang 11-Jul-12 5:24am    
Hmm, where did you copy that from, maybe you should tell the author to correct this line:
delete [] NULL;
to:
delete [] buffer;

To answer your first question:

There are two reasons it is being done. firstly we want our class to hold the data in its own memory location rather than start pointing to the existing memory that was allocated outside of the class. if we dont put strcpy there and simple assign the pointer then that would result in a shallow copy and when the char* that was supplied from outside goes out of scope(or deleted) this class must have ended up pointing to some invalid location. secondly why is is not buffer*, simple reason for this is the starting address of char array needs to be passed to strcpy to copy the data from source to destination. if we pass buffer* that would actually be a pointer pointing to the starting address of the array, resulting in wring results and perhaps catastrophe.
C++
strcpy(Buffer, InitialInput);


Now to answer your second question

C++
const char * GetString()
{
    return Buffer;
}


The reason this is returning a * is because we want the caller to get hold of complete string. that can only be done by passing the pointer to starting address. the caller can then simply use this address extract all chars till a \0 and have all the string.

Now why is is const, we dont want the called to be able to change the string from outside and thus we are passing a const.

ADDITIONAL THOUGHTS:

I think this function getString is returning a pointer to a constant string so that the data can not be changed from outside but it is actually violating the basic encapsulation by passing the member pointer outside of the class. if he really wishes to so this I think this should ideally be like

C++
const char * const GetString()
{
    return Buffer;
}


I made the pointer constant too.

Note: C++ Gurus, please correct me if I am wrong or perhaps refine my understanding, i would really appreciate that.

eagerly awaiting response of experts on this.
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 11-Jul-12 0:50am    
Good answer, more useful detail, my 5.
--SA
nurza 11-Jul-12 1:06am    
Oh now I understand.

I did not link together that InitialInput has the starting address of char array and that strcpy copies the starting address in InitialInput to Buffer.

The reason this is returning a * is because we want the caller to get hold of complete string. that can only be done by passing the pointer to starting address

Thank you for explaining that one to me. I have not learn that one yet and this is my first time encountered this code. I should check more examples on this.
Rahul Rajat Singh 11-Jul-12 1:13am    
you are welcome. if it worked then please mark the answer as solution as this would let other know that the problems is solved and the others with similar problem can also refer and benefit from it.
[no name] 11-Jul-12 2:11am    
You said correctly Rahul. 5+
Answer #1: because this is how the function strcpy is defined:
http://www.cplusplus.com/reference/clibrary/cstring/strcpy/[^].

More seriously: the syntax you were thinking about would not work. First, you de-reference the pointer, get a value of a primitive type, then, you pass this value using call-by-value strategy. In this way, you would pass just the value, loosing any information of the addresses originally used to store this value. So, it would not be possible to implement strcpy based on this insufficient information. You really need a pointer to make it working (and you don't need value of a first element in a buffer, the one you would obtain as *Buffer).

Please see:
http://en.wikipedia.org/wiki/Call-by-value#Call_by_value[^].

Answer #2: The return type is const char *, followed by a function name GetString. This function will return the value of the type const char *. I guess, the question is: what's the constant here: the pointer or the area of memory pointed by the pointer? The answer is: the pointer itself is not constant, the pointed area of memory is. It means not that the characters are immutable; it means that you cannot modify the values of the characters through this pointer:

C++
const char * p = GetString();
//will not compile:
p[3] = '?';


The restriction is purely syntactic.

—SA
 
Share this answer
 
v6
Comments
Rahul Rajat Singh 11-Jul-12 0:45am    
+5 from me.
Sergey Alexandrovich Kryukov 11-Jul-12 0:49am    
Thank you, Rahul.
--SA
nurza 11-Jul-12 1:12am    
Thank you Sergey. Your explanations gave more info on what Rahul has explained.
Sergey Alexandrovich Kryukov 11-Jul-12 14:51pm    
You are welcome.
If so, please accept the answer formally (green button) -- thanks.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900