Hi,
I am still struggling to master C++ and is trying to understand how to
achieve passing arguments using pointers. I got some questions that I
like to post to the experts here, hope you can help to clarify my
doubts. I'm using g++ version 3.3.4. I created 3 classes as below for
testing some concepts. The questions are written as comments in
Bclass.h file. Thank you for your time and tips!
------------runtime errors------------
{8=> main
Aclass created.
Bclass instantiated.
main: Aclass.h:19: void Aclass::test(): Assertion `b' failed.
Aborted
-------------file: main.cc------------
#include "Aclass.h"
int main(){
Aclass a;
a.test();
}
-------------file: Aclass.h-----------
#ifndef ACLASS_H
#define ACLASS_H
#include "Bclass.h"
#include <stack>
#include <cassert>
class Aclass{
public:
Aclass(){
std::cout << "Aclass created." << std::endl;
}
~Aclass(){ std::cout << "Aclass destructed." << std::endl; }
void test(){
Bclass *b=NULL;
if( box.empty() ){
create(b);
assert(b); // As expected this fails during runtime
/* Qn: Is the failure because pointer 'b' is pointing to NULL?
* Qn: Is the reason why the call to "create" function without effect
* because the local pointer 'ptr' was changed to point to a temporary
object?
*/
}
delete b;
}
protected:
void create(Bclass *ptr){
box.push( new Bclass() );
ptr = box.top();
box.pop();// memory is pop
assert(ptr); // this is fine
/* Qn: Is the reason the assertion pass because local pointer 'b' is
* still referencing the memory?
* Qn: Is the memory release or considered unreferenced only if
* we get out of the "create" function?
*/
}
private:
std::stack<Bclass* > box;
};
#endif
-------------file: Bclass.h-----------
#ifndef BCLASS_H
#define BCLASS_H
#include <iostream>
class Bclass{
public:
Bclass(){ std::cout << "Bclass instantiated." << std::endl; }
~Bclass(){ std::cout << "Bclass destroyed." << std::endl; }
};
#endif