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.
You forgot
*:It should be
*pchChar, notpchChar. Because you’re printing it as%c.Or you can use
%sas 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:Or even better use
new, andstd::cout.Also, don’t forget to call
freewithmallocto deallocate the memory once you’re done with it. And if you usenew, usedelete.