Sunday, July 12, 2009

What are the problems with these C++ (cpp) codes?

I am new to C++ (migrate from Java). I am asked to say what is the problem with these pieces of code?





Q:





struct MyStruct


{


int *p;


MyStruct(int n) { p = new int; *p = n; }


~MyStruct() { delete p; }


};





--------------------------------------...


Q:





int *array(int n)


{


return new int(n);


}





int main()


{


int *p = array(10);


for( int i = 0; i %26lt; 10; i++ )


{


p[i] = 0;


}


printf( "%d\n", p[0] );


p = array(10);


printf( "%d\n", p[0] );


return 0;


}








--------------------------------------...


Q:








class A { public: int a, b; };


class B


{


public:


const A a;


B() :a() { }


};





int main()


{


B b;


printf( "%d %d\n", b.a.a, b.a.b );


return 0;


}





Is there a C++ guru that can help?





Thanks

What are the problems with these C++ (cpp) codes?
First:








struct MyStruct


{


int *p;


MyStruct(int n) { p = new int; *p = n; }


~MyStruct() { delete p; }


};


Nothing wrong here, far as I can tell...





An initializer like:


MyStruct bob(4);


ought to work just fine.


When bob goes out of scope, it ought to de-allocate the byte for *p.





Compiles fine.





As for the second:





int *array(int n)


{


return new int(n);


}





int main()


{


int *p = array(10);


for( int i = 0; i %26lt; 10; i++ )


{


p[i] = 0;


}


printf( "%d\n", p[0] );


p = array(10);


printf( "%d\n", p[0] );


return 0;


}





Here's the deal. The


new operator in the array function is declared locally to the array function. As soon as we hit the }, the array will go out of scope and be de-allocated immediately. You're going to be writing to an indeterminate location in memory subsequent to the array() call.


Better to just call the new operator in the same scope as where you're going to be using it, or declare your array() as a macro.








As for the third:





What the heck are you trying to do here?








As for the previous answerer who brought into question the difference between C and c++, I gotta say: "Every C program IS a c++ program!"


C++ is an extension to c.


C is C++!





Question: What is the difference between:


class bob


{


public:


int b;


};


and


struct bob


{


int b;


};


??





NOTHING! A struct is just a class that defaults to public.


Try it.


class just defaults to private.





---EDIT---


structs %26gt;%26gt;can%26lt;%26lt; have methods in c++
Reply:Q1,





structs don't have methods. Well, not that I know of.





Q2.





If I'm correct, the call was made to the array function which returned an int, not an integer array. Hence you can't loop through it.





Q3.





I dunno what this is. B() :a() { }


Also, there weren't any values assigned to "a", "b".





b declared by class B is still null.


a declared by const A is still null.

salary survey

No comments:

Post a Comment