K
kk
Hi Guys, i am posting a cpp program contains runtime error, memory not
allocated to char *x in class B. while accessing showx function it
doesn't print values. if anybody knows send a reply plz.
thanks in advance
kiran
#include <iostream.h>
#include <string.h>
#include <stdio.h>
class B{
char *x;
public:
B(char *y="xxx"){
cout<<"string of x"<<y<<endl;
x=new char[strlen(y)+1];
if(!*x)
strcpy(x,y);
else
cout<<"memory allocation failure"<<endl;
}
B(B *objb):x(new char[strlen(objb->x)+1])
{
strcpy(x,objb->x);
}
B(const B& objb)
{
x=new char[strlen(objb.x)+1];
strcpy(x,objb.x);
}
void showx()
{
cout<<"value of x from the object of class
B="<<x<<endl;
}
~B(){
if(*x)
delete []x;
}
};
class A{
char *y;
B *b;
public:
A(char *c="xxx",char *d="bbb"){
y=new char[strlen(c)+1];
b=new B(d);
if(!*y||!*d)
{
cout<<"memory allocation failure"<<endl;
}
strcpy(y,c);
}
void showy()
{
cout<<"value of x from the object of class
B="<<y<<endl;
b->showx();
}
~A(){
if(*y)
delete []y;
else
cout<<"memory was already deleted"<<endl;
}
};
main()
{
A a("Hello","World");
a.showy();
}
allocated to char *x in class B. while accessing showx function it
doesn't print values. if anybody knows send a reply plz.
thanks in advance
kiran
#include <iostream.h>
#include <string.h>
#include <stdio.h>
class B{
char *x;
public:
B(char *y="xxx"){
cout<<"string of x"<<y<<endl;
x=new char[strlen(y)+1];
if(!*x)
strcpy(x,y);
else
cout<<"memory allocation failure"<<endl;
}
B(B *objb):x(new char[strlen(objb->x)+1])
{
strcpy(x,objb->x);
}
B(const B& objb)
{
x=new char[strlen(objb.x)+1];
strcpy(x,objb.x);
}
void showx()
{
cout<<"value of x from the object of class
B="<<x<<endl;
}
~B(){
if(*x)
delete []x;
}
};
class A{
char *y;
B *b;
public:
A(char *c="xxx",char *d="bbb"){
y=new char[strlen(c)+1];
b=new B(d);
if(!*y||!*d)
{
cout<<"memory allocation failure"<<endl;
}
strcpy(y,c);
}
void showy()
{
cout<<"value of x from the object of class
B="<<y<<endl;
b->showx();
}
~A(){
if(*y)
delete []y;
else
cout<<"memory was already deleted"<<endl;
}
};
main()
{
A a("Hello","World");
a.showy();
}