Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The compiler is telling me I can't make the assignment in the constructor. I have extremely similar code in another class and it compiles just fine.
Dependency.h
class Dependency {
public:
Dependency(std::function<void ()> const & func);
private:
std::function<void ()> const call_back;
};
Dependency::Dependency(std::function<void ()> const & func){
call_back = func;
}
Dependency::Dependency(std::function<void ()> const & func){
call_back = func;
}
First, this constructs a Dependency object, and it's call_back member. Then it enters the {}, which attempts to reassign func to call_back, which isn't allowed, because call_back is const.
Instead, we have to tell the compiler to construct call_back with func the first time, which uses this magic syntax:
Dependency::Dependency(std::function<void ()> const & func)
:call_back(func)
{
}
You use the same technique to call a specific constructor for parent classes. Please note that it ignores the order you use here, the compiler will instead always construct the parent class(es) first, and then the members in the order they were declared in the class definition.
A const member can't be assigned after initialization. You have to ensure it is properly initialized in the constructor initialization list.
Dependency::Dependency(std::function<void()> const& func) : call_back(func) {}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Suppose I have
struct B
{
template<typename T>
void doSomething(T& bar);
};
class A
{
//... (ctor etc.)
template<typename T>
void foo(const std::string& name, T& bar)
{
for(auto& data : myData)
{
if(data.first == name)
*(data.second)->doSomething(bar); //ERROR
}
}
private:
std::vector<std::pair<std::string, B**>> myData;
};
I thought this would work because we are iterating over 'myData' by reference, i.e. no copies, and then we do *(data.second) to access a pointer to B, which we then use the '> operator to access its 'oSomething Method.
Instead, I am just getting the error:
member reference base type 'B' is not a structure or union*
which makes no sense to me since B* is a pointer to a struct, and using the '->' operator on that would dereference the pointer revealing the actual class.
GodBolt Reproduction: https://godbolt.org/z/c45oMT
And the error mentioned in the question is because *(data.second)->doSomething(bar) is really the same as *(data.second->doSomething(bar)).
That is you try to call data.second->doSomething(bar) which is not possible because data.second is a pointer to a pointer to an object.
Then you attempt to dereference whatever doSomething returns, which also isn't possible since it doesn't return anything.
What you probably want is something like
(*data.second)->doSomething(bar);
This will first dereference data.second removing one indirection, resulting in a pointer to B (i.e. *data.second results in a B*). Then call the function on that object.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Cant pass a const data type into a non const function. After setting the func to type const the error on
assigning a value in the function will understandably set of an error because its not mutable as its inside
a function of type const.
How can I pass a const varaiable into a non const function by reference, and allow contents of the function
to be modified?
error C2662: void CarFactory::set_values(Car &) cannot conver this pointer from const Car to Car &
// Tried this
//Car& newCarData = const_cast<Car&>(myCar);
const Car& myCar = volvo->GetBuild();
// Tried this
//Car& newCarData = const_cast<Car&>(myCar);
set_values(&myCar);
void CarFactory::set_values(const Car& myCar){
// do some assigning here for mutable variables declared in the header
}
Should be able to call this without the error and pass through the data to set_values(). And also modify non const variables set in the header.
If you want to modify the Car object in set_values you must pass it a non-const reference. But that means that your volvo->GetBuild() must return a non-const reference too.
Solution below, not great but works for this. Backdoor pointer if you will.
CarFactory* ptr = const_cast<CarFactory*>(this);
In the end, I apologise for not having a minimal working version of code in the question. Tried to explain it where if you know consts you might be able to bounce some ideas around. The comments mentioned did support this solution so thank you.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a class defined in a hpp file which I'm trying to use in another header, so I made a forward declaration to it (I only want to use it by reference as a function parameter). For some reason I keep getting a compile error because of it. I can't figure out why it's not working. Here are my codes:
//something.hpp:
class MyClass;
void someFunction (MyClass& mc);
...
//something.cpp:
#include "MyClass.hpp"
void someFunction (MyClass& mc) {...}
...
//MyClass.hpp:
class MyClass {
const char* myText;
public:
MyClass (const char* text) : myText(text) {}
};
//main.cpp:
int main () {
...
someFunction (MyClass ("some text here"));
...
}
And I get an error from main() which says:
'<function-style-cast>' : cannot convert from 'const char [15]' to 'MyClass'
Source or target has incomplete type
If I understand it right, it means that the compiler doesn't find the definition of MyClass, only the predeclaration of it (even though I included MyClass.hpp in something.cpp), that's why it says it's incomplete. What did I miss here?
The function
void someFunction (MyClass& mc);
is accepting a non-const reference to a MyClass instance.
You are not allowed to pass a temporary to such a function.
The code should be
#include "MyClass.hpp"
...
int main() {
MyClass m("some text here");
someFunction(m);
}
or alternatively you need to accept a const reference.
void someFunction (const MyClass& mc);
I don't think that the problem is related to the forward declaration, but rather that you cannot pass a temporary to a function taking a reference as argument. In fact, if you put all your definitions in a single file, it still doesn't compile. On the other hand, if you replace the code of the main with the following, it will compile:
int main() {
MyClass mc("Some text here");
someFunction(mc);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
as little follow up to this: C++ lambda function without C++0x?
I have created the lambda function as a function object without c0x
the question now is:
how to pass it as a callback/function pointer to another function?
My first try was like this, but it didn't work:
Lambda Obj( C, D);
command ( Obj.operator()(typeA A, typeB B));
I marked the other question to early i guess, so noone looked at the edit.
If you cannot find std::function in std::tr1::function or via std::function or via a compiler upgrade...
Write your own std::function-like type eraser, or use boost, or use 'the fastest possible delegates' (that should google to a complete implememtation), or pass both a this pointer and a method pointer as template-type-deduced arguments to a function, or pass a template-type-deduced copy of the function object to the function.
Note that the last two options require the function's body to be exposed (such as in a header file).
Or convert the function object into a void* style C callback.
I would go with C++11, and failing that boost, and failing that fast delegates, failing that write a type eraser myself, failing that stick body in header and template+pass a copy (unless function is simple, in which case do this first), and failing that pvoid C style.
Using Boost.Bind:
void command(boost::function<void()> func)
{
func();
}
Lambda Obj(C, D);
command(boost::bind<void>(Obj, A, B));
(or maybe you wanted to have):
void command(boost::function<retType(typeA, typeB)> func)
{
retType ret = func(A, B);
}
Lambda Obj(C, D);
command(boost::bind<retType>(Obj, _1, _2)); // placeholders
Using templates (the STL's way):
template <typename F>
void command(F func)
{
func(A, B);
}
Lambda Obj(C, D);
command(Obj);
Live demo link.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can a constructor be private in C++? If yes then how can we call it?
class Puma
{
int a = 10;
Puma()
{
cout << a;
}
};
int main()
{
Puma pum;
return o;
}
Can this program run? If not then how can we call Puma() constructor as it is private?
Yes, a constructor can be private. And you can call it with member functions (static or non) or friend functions.
class Puma
{
public:
static Puma create(int a) { return Puma(a); }
private:
int age;
Puma(int a) :age(a) {}
friend Puma createPuma(int a);
};
Puma createPuma(int a) { return Puma(a); }
For possible use cases, see the Factory Pattern, or the Named Constructor Idiom.
Yes. Constructor may be private.
In this case you may create class
Using another (public) constructor
Calling constructor from the same class
Calling constructor from the friend class/function
In your code, the program cannot run since you have defined a constructor and it is private. Therefore, in your current code, there is no way to create objects of the class, making the class useless in a sense.
One way to do is that you can provide public static functions, those static functions call the private constructors to create objects of class.
One minor thing:
return o;
should be
return 0;
Yes a constructor can be private. It is useful when called by a static member function (or a friend), e.g.
class Even {
/// in practice, some more C++ code is probably needed
private:
int x;
Even(int a) : x(a) {};
public:
int get () const { return 2*x; };
static Even* make(int y) { return new Even(y); };
};
the example is not very realistic, but you get the idea. In the using code, do
Even* e = Even::make(3);
Be however aware of the C++ rule of five and do read a good C++ programming book and the documentation of your C++ compiler (e.g. GCC or Clang) and of your debugger (e.g. GDB). You may even want to use the Clang static analyzer.
For examples, download, then look inside the source code of Qt, of FLTK, of RefPerSys, of fish, of GCC or Clang.
Singleton can have a private constructor that will be called from a static method of a class.