Reputation: 733
class Base {
protected:
string m_strName;
char* pchChar;
public:
Base()
{
m_strName = "Base";
pchChar = NULL;
};
void display()
{
printf(" display name : %s %c\n",m_strName.c_str(),pchChar);
};
};
class Derived : protected Base {
public:
Derived()
{
init();
};
void init()
{
m_strName = "Derived";
pchChar = (char*)malloc(sizeof(char));
strcpy(pchChar,"A");
printf(" char %c\n",*pchChar);
display();
};
};
int main()
{
Derived* pDerived = new Derived();
return 0;
}
The observed output is
char A
display name : Derived P
whereas i expected pchChar should have value "A" on both occasions. am i missing any piece of information?? pls suggest.
Upvotes: 0
Views: 386
Reputation: 881363
printf(" display name : %s %c\n",m_strName.c_str(),pchChar);
should be:
printf(" display name : %s %c\n",m_strName.c_str(),*pchChar);
The first will coerce the pointer into a character and will therefore depend entirely upon where that character is located in your address space.
The second will correctly dereference the pointer to get at the character, exactly as you have done so in the init
code of your derived class.
And this little snippet:
pchChar = (char*)malloc(sizeof(char));
does not allocate enough space for the "A"
string, you need two characters for that:
pchChar = (char*)malloc(2); // sizeof(char) is ALWAYS 1 !!!
Or better yet, don't use malloc
at all. Although C++ provides those facilities for C compatibility, you're probably better off using new
and delete
.
Upvotes: 2
Reputation: 361362
You forgot *
:
printf(" display name : %s %c\n",m_strName.c_str(), *pchChar);
It should be *pchChar
, not pchChar
. Because you're printing it as %c
.
Or you can use %s
as format string, and your printf would work, if the c-string is null-terminated string. Currently its not null-terminated. You should be doing this:
pchChar = (char*)malloc( 2 * sizeof(char)); //2 chars, one for `\0`
strcpy(pchChar,"A");
Or even better use new
, and std::cout
.
Also, don't forget to call free
with malloc
to deallocate the memory once you're done with it. And if you use new
, use delete
.
Upvotes: 2