"kk" <> wrote in message
news: oups.com...
Hi all,
i didn't get output in the following code while compiling and executing
with g++ version 3.2.3 it doesn't allocate memory to pointer varaible
(x) in class B. and it gives correct output while executing in .Net and
visual slick editor. why it didn't allocate memory? if anybody knows
plz give reply.
thanks in advance
kk
------File Name: les9_5.C--------------
#include <iostream>
#include <string.h>
using namespace std;
class B{
char *x;
public:
B(char *y="xxx")

(new char[strlen(y)+1]){
try{
// x=new char[strlen(y)+1];
A few things:
1) you've commented out the allocation above, and replaced it with an
initializer list. Why put the "new" in the initializer, but keep this
useless code below which checks if x is allocated or not? In a conforming
compiler, new throws an exception if it fails. Why do you want all this
code below? If the exception happens, it will happen in the initializer
list above, before you enter the try, where you actually _could_ catch it.
2) Why are you BOTH checking if the pointer is nil AND trying
(unsuccessfully) to catch the allocation exception? Remove the if statement
test.
3) What if y is nil? Your code should probably be testing if y is nil (not
if x is nil), and if it's not, THEN allocate memory for x and copy y to it.
(Otherswise I assume x should be nil?)
4) Suppose in your code that you did catch an exception somehow. You're
allowing the constructor to continue, reporting via cout that an error
occurred. But there's still a problem, in that x was never properly
allocated. How's the rest of your program going to like that? If you want
to report an exception via cout, that's fine, but you need to be sure you
either re-throw the exception or else take some appropriate action to make
sure your object is in a viable state.
if(*x)
strcpy(x,y);
else
{
cout<<"value at x\t"<<x<<endl;
cout<<y<<endl;//checkig formal
parameter
throw 1;
}
}catch(...){
cout<<"Constructor B(char *y=\"xxx\") "<<endl;
cout<<"memory allocation failure"<<endl;
}
}
-Howard