I don't understand why can you do this:

Employee *emp;

    if (condition1)
      emp = new Employee();
   else if (condition2)
      emp = new Manager();

but not this:

Employee emp;

    if (condition1) 
      emp = Employee();
   else if (condition2) {
      emp = Manager();

Maybe this is a TERRIBLE idea, but it seems to me if you don't use pointers then you never have memory leak type problems... but the language disallows you from NOT using pointers in cases like this.

Any comments?

Thanks,

Dave

it seems to me if you don't use pointers then you never have memory leak type problems...

I wish that were so. :( Raw pointers are dangerous, and that's why smart pointers and RAII are so important. Even if you use the troublesome auto_ptr, your leak problem can be fixed:

std::auto_ptr<Employee> emp;

if (condition1)
    emp.reset(new Employee());
else if (condition2)
    emp.reset(new Manager());

The reason your second example does not work is because the new object goes out of scope at the end of the conditional block. If you use new then the object is not bound by scope restrictions as long as you have a pointer to it.

I see, it's a scope problem. So why isn't there something like this:

Employee emp;
    if (condition1) 
      emp.setClass(Employee());
   else if (condition2) {
      emp.setClass(Manager());

I mean clearly that is not a real syntax, but then there are no scope problems and you still didn't have to use pointers.

I see your point, but why add new rules that could break a lot of existing code when RAII and libraries already cleanly solve the memory leak problem? Is there something else you're worried about besides memory leaks that makes you want to avoid pointers?

No - it's just some ridiculous fear of them I have haha. I understand the syntax and semantics of them, but if I started coding I would never say MyClass* A; before MyClass A; . I guess if you start from the ground up it may be ok, but if I already have a lot of code that depends on receiving real objects, not just pointers, then it is a bear to have to go through and change everything to pointers - know what I mean?

Each has its own purpose: MyClass A; will disappear from view then the function exits (unless its global), and you can not specify the type of object, whether it is grandfather of class B or class C. The only way to do that is to use a pointer.

class BaseClass
{
   // blabla
};

class Derived1 : public BaseClass
{

};

class Derived2 : public BaseClass
{

};

int main()
{
    vector<BaseClass*> bList;
    BaseClass* pBase = 0;
    if( <condition1> )
      pBase = (BaseClass *)Derived1;
   else
      pBase = (BaseClass *)Derived2;

   bList.push_back(pBase);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.