13

I feel like this should be simple but for whatever reason I can't get it to work.

I'm trying to create an instance of a class that can be passed into and edited directly by other functions.

For example:

main()
{
    ClassFoo foo = new ClassFoo();
    someFunction(foo);
}

void someFunction(ClassFoo& f)
{
    f.add("bar");
}

The problem is, when compiling, I end up with this error.

no viable conversion from 'ClassFoo *' to 'ClassFoo'
    ClassFoo foo = new ClassFoo();
             ^    ~~~~~~~~~~~~~~~

It also says that other candidate constructors are not viable, however in my ClassFoo class I do have a constructor that looks like this:

ClassFoo::ClassFoo()
{}

So how would I be able to accomplish editing the ClassFoo variable in functions?

0

2 Answers 2

18

C++ is not Java (or C# I suppose). You should never use the new keyword unless you know that you need to. And it returns a pointer to the newly created class, hence the error you get. Likely, the following would be sufficient:

Class foo;
someFunction(foo);

For a default constructed object, you shouldn't include the () if you're not using new, as this does something completely different (see the most vexing parse)

4
  • The only time when you probably need to use new in modern C++ is when specifying custom deleters for smart pointers. +1
    – vsoftco
    Mar 19, 2015 at 2:45
  • Thank you for this. Any idea why when exiting the program (just returning 0 in main), it says that pointer being freed was not allocated?
    – Alex
    Mar 19, 2015 at 3:08
  • @Alex That implies somewhere you have a delete call that's trying to delete something that was not allocated with new. See: stackoverflow.com/questions/22824802/… . But like how new shouldn't show up unless you really know you need it, neither should delete.
    – aruisdante
    Mar 19, 2015 at 3:15
  • Class foo(); would be a function declaration. Class foo{}; would more closely match what you are saying (although if the class were an aggregate then the {} would be significant)
    – M.M
    Mar 19, 2015 at 3:20
6

You're probably used to C# or similar sintax..

However, in C++, there are big differences between these lines:

ClassFoo foo; //local variable at stack
ClassFoo *foo = new ClassFoo(); //local pointer to some memory at heap which is structured like ClassFoo

You probably wanted first line just to create local object. There are numerous tutorials that describe difference between heap and stack.. so check them out

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.