CFD Online Discussion Forums

CFD Online Discussion Forums (http://www.cfd-online.com/Forums/)
-   OpenFOAM (http://www.cfd-online.com/Forums/openfoam/)
-   -   autoPtr, derived classes and memory leak (http://www.cfd-online.com/Forums/openfoam/66936-autoptr-derived-classes-memory-leak.html)

johndeas July 28, 2009 17:50

autoPtr, derived classes and memory leak
 
Hi,

i am trying to understand generic programming concepts used in OpenFOAM, and have a basic question in C++.

suppose I have a "employee" base class which has virtual functions, and two derived classes:
Code:

employeeExportA:public employee
and
Code:

employeeExportB:public employee
I want to have a pointer to the employee base class called myEmployee, and be able to choose at runtime wether it points to a employeeExportA or employeeExportB object. I tried this code:

Code:

    auto_ptr<employee> myEmployee;
    if (inputString == "A")
    {
        myEmployee = auto_ptr<employeeExportA>(new employeeExportA(4,5));
    if (inputString == "B")
    {
        myEmployee = auto_ptr<employeeExportB>(new employeeExportB(4,5));;
    }

My program compiles, but I would like to know, since the auto_ptr myEmployee has been created with the base class, will it be able to clean all the memory created by the "new" operator applied to a derived class, or will it only clean the part of the object in common with the base and let the remaining leaking ?

gschaider July 29, 2009 05:29

Quote:

Originally Posted by johndeas (Post 224479)
Hi,

i am trying to understand generic programming concepts used in OpenFOAM, and have a basic question in C++.

suppose I have a "employee" base class which has virtual functions, and two derived classes:
Code:

employeeExportA:public employee
and
Code:

employeeExportB:public employee
I want to have a pointer to the employee base class called myEmployee, and be able to choose at runtime wether it points to a employeeExportA or employeeExportB object. I tried this code:

Code:

    auto_ptr<employee> myEmployee;
    if (inputString == "A")
    {
        myEmployee = auto_ptr<employeeExportA>(new employeeExportA(4,5));
    if (inputString == "B")
    {
        myEmployee = auto_ptr<employeeExportB>(new employeeExportB(4,5));;
    }

My program compiles, but I would like to know, since the auto_ptr myEmployee has been created with the base class, will it be able to clean all the memory created by the "new" operator applied to a derived class, or will it only clean the part of the object in common with the base and let the remaining leaking ?

That depends. Google for "virtual destructor"


All times are GMT -4. The time now is 03:38.