Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No viable conversion from 'Class *' to 'Class' C++

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?

like image 780
Alex Avatar asked Mar 19 '15 02:03

Alex


1 Answers

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)

like image 186
aruisdante Avatar answered Sep 18 '22 15:09

aruisdante