Initialize member function arguments as data members in c++ - c++

When trying to implement a class like this
class sample{
int a;
public:
sample(int a = 0){
this->a =a ;
}
void fun(int base = /*the value of a*/){
// some function code
}
};
I want to initialize the argument base of the function fun with the value of a (the data member of the class).
Writing int base = a or int base = this->a doesn't work.
So, I thought I could overload the function this way.
void fun(void){
fun(a);
}
void fun(int base){
// some function code
}
This will actually work, but is there any better/smarter way to do the same thing? Because I have many other functions, I want to implement the same way. And I don't want to overload each of them.
Thanks.

You can make it explicit with std::optional. Before that (or Boost.Optional or whatever), the usual solution would be to sacrifice a magic value that base could never legally take (such as -1 in the other answer).
class sample{
int a_;
public:
sample(int a = 0) : a_(a) {}
void fun(std::optional<int> base = std::nullopt){
if (!base) base = a_;
// some function code
}
};
Or, as Jarod42 suggests, something like
void fun(std::optional<int> base_opt = std::nullopt){
int base = base_opt.value_or(a_);
// some function code
}
NB.
Writing int base = a or int base = this->a doesn't work
Yeah, there is no instance at the point where the function is declared, and that's when the default expression is evaluated.
I was under the impression that private members, when they're inaccessible at the call site, would be prohibited - but that isn't correct. So the expression must be evaluated when the function is declared, with the function's own access and symbol visibility at that point, even though it is executed at the call site.

Sentinel values
This can be achieved via a "sentinel" value. If a particular integer is unused (such as -1), try:
void fun(int base = -1) {
if (base == -1) {
base = this->a;
}
// ...
}
std::optional
Another way is to wrap the input up with an std::optional:
void fun(std::optional<int> base = std::nullopt) {
if (!base) {
base = this->a;
}
// Extract actual value by using *.
int base_value = *base;
// Use base_value.
// ...
}
In the example above, base_value is the "default"-corrected int that you desired. A more elegant alternative is to use std::optional<T>::value_or to extract the value:
void fun(std::optional<int> base = std::nullopt) {
int base_value = base.value_or(this->a);
// Use base_value.
// ...
}

Overload of fun is simple and clean:
class sample{
int a;
public:
sample(int a = 0){
this->a =a ;
}
void fun(){
fun(a);
}
void fun(int base){
// some function code
}
};

Related

Provide a pointer to member function to be invoked by the target class without functional

I'm reading a lot of questions (and answers) about function pointers, functors and callbacks but I still have a confusion about which is the right tool for me.
Some of them cannot apply to my scenario because it seems my compiler avr-gcc v5.4.0 does not have C++ standard library (i.e. std::function is not available).
This is my base class:
class Debouncer
{
public:
typedef uint8_t (Debouncer::*debouncer_raw_t) (void);
Debouncer() {}
void setRawFunction(Debouncer::debouncer_raw_t callback) { _raw = callback; }
private:
debouncer_raw_t _raw;
void anotherFunction()
{
uint8_t value = _raw();
// do something
}
}
In my other classes I have:
class Inputs
{
public:
Inputs()
{
_deb.setRawFunction(myRaw);
}
private:
Debouncer _deb;
uint8_t myRaw()
{
return something;
}
}
Of course this won't compile because myRaw is not static.
Anyway, I'm going to try to avoid this because it would break the existing code.
If I'm not wrong, a lot of questions seem to ask the other way around.
Instead I just want to pass the pointer of my member function to my Debouncer class, so it can call _raw() when it needs to.
Here I found this advise to avoid std:: library:
#define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember))
void userCode(Fred& fred, FredMemFn p) // Use a typedef for pointer-to-member types
{
int ans = CALL_MEMBER_FN(fred,p)('x', 3.14);
// Would normally be: int ans = (fred.*p)('x', 3.14);
// ...
}
But it seems the other way around. Here the class Fred is my Debouncer.
I don't want to call the Debouncer member, but member of the caller class (i.e. Input::myRaw()).
Would you please help me to understand which is the right tool to achieve such a simple task?
Making a member function virtual is a relatively low-overhead way to have a single pointer (to an object) refer to both the object's data and the correct member function.
class InputsBase
{
// All classes that implement myRaw() should inherit from this class
public:
virtual uint8_t myRaw() = 0;
};
class Inputs : public InputsBase
{
public:
Inputs()
{
_deb.setRawFunction(this);
}
private:
Debouncer _deb;
virtual uint8_t myRaw()
{
return something;
}
}
Your Debouncer can then simply store a pointer to the object in question.
class Debouncer
{
public:
typedef InputsBase* debouncer_raw_t;
Debouncer() {}
void setRawFunction(debouncer_raw_t callback) { _raw = callback; }
private:
debouncer_raw_t _raw;
void anotherFunction()
{
uint8_t value = _raw->myRaw();
// do something
}
}
If you know (or require) each of the classes using Debouncer have a public myRaw() function (or better operator(), or actually anything else), the problem is simpler:
template <typename T>
class Debouncer
{
public:
Debouncer (T* t): _t(t) {}
void anotherFunction()
{
uint8_t value = _t->myRaw();
std::cout << static_cast<int>(value);
}
private:
T* _t;
};
class Inputs
{
public:
Inputs() : _deb(this)
{
// beware, if Debouncer uses its parameter in constructor (like call a method),
// you cannot use initializer list
}
uint8_t myRaw()
{
return 13;
}
void foo()
{
_deb.anotherFunction();
}
private:
Debouncer<Inputs> _deb;
};
int main()
{
Inputs i;
i.foo();
}
This would be preferred solution in C++. See for example standard library <algorithm> - any function taking a predicate or some other callable expects to call it with operator() rathen than having to deal with pointers-to-member-function.
If you don't know what function should be called and you really cannot impose any requirement on the classes, you need to store both a pointer (or reference) to the class and a pointer to the member function. Note that you cannot connect pointers to member functions of different classes, so we need templates once again:
template <typename T, typename Func>
class Debouncer
{
public:
Debouncer (T* t, Func f): _t(t), _f(f) {}
void anotherFunction()
{
uint8_t value = (_t->*_f)(); //I get it now why isocpp asks to use macro here, the syntax is horrible
std::cout << static_cast<int>(value);
}
private:
T* _t;
Func _f;
};
class Inputs
{
public:
Inputs() : _deb(this, &Inputs::myRaw)
{
// beware, if Debouncer uses its parameter in constructor (like call a method),
// you cannot use initializer list
}
uint8_t myRaw()
{
return 13;
}
void foo()
{
_deb.anotherFunction();
}
private:
Debouncer<Inputs, decltype(&Inputs::myRaw)> _deb; //decltype is C++11, you could also declare type like you did in your question
};
int main()
{
Inputs i;
i.foo();
}

How to call a class member function recursively from its own defintion in C++?

I'm new to C++ and I need a class member function to call itself from its own definition, like this -
class MyClass {
public: // or private: ?
// Some code here
// ...
void myfunction();
// ...
};
void MyClass::myfunction()
{
// Some code here
// ...
// Call MyClass::myfunction() here, but how?
// ...
}
but I don't know the proper syntax for it and how can it be called by itself without creating an object usually done like this - object_name.member_function(), if possible?
And, will there be any difference if myfunction() belongs to public: or private:?
Since the function isn't static, you already do have an instance to operate on
void MyClass::myfunction()
{
// Some code here
// ...
this->myfunction();
// ...
}
You could leave the this-> off, I was just being more clear about how the function is able to be called.
myfunction() is in the scope of the class, so you can "simply" call it:
class MyClass {
public:
// Some code here
// ...
void myfunction();
// ...
};
void MyClass::myfunction()
{
myfunction();
}
Note, however, that this will give a stack overflow. You need a means to stop the recursion.
Member functions are actually a form of syntactic sugar. They describe a function that somehow secretly takes a pointer to an object instance which, inside the function, is accessible as this.
struct Foo {
vod bar();
};
Foo foo;
foo.bar();
What you're really doing in the call here is calling a Foo::bar(&foo); and bar is really taking a pointer Foo* this. How that's done varies from implementation to implementation, some compilers/architectures will use a special register to track the current object.
An additional piece of syntactic sugar makes all member variables and functions visible to you within a member function as though they are locally scoped
struct Foo {
int i;
int add(int n) {
return i + n;
}
int addx2(int n) {
return add(n) * 2;
}
};
What's actually happening here is:
return this->i + n;
and
return this->add(n) * 2;
This means its very easy to run into situations where you have conflicts between local and member names.
struct Foo {
int i;
Foo(int i) {
i = i; // not what you expected
}
};
For this reason, many engineers make careful use of case or prefixes or suffixes to help them distinguish members, parameters and variables.
struct Foo { // Uppercase for types and functions
int m_i; // m_ for member
Foo(int i_, int j_) {
int i = sqrt(i));
m_i = i + j_;
}
int Add(int i) {
return i_ + i;
}
};
There are various different patterns people use - some people use _name to denote a member, some use name_ and fn_ to denote members.
struct Foo {
int i_;
int add_(int _i) {
return i_ + _i;
}
};
The main thing is to be consistent.
but I don't know the proper syntax for it and how can it be called by itself without creating an object usually done like this - object_name.member_function(), if possible?
Use:
void MyClass::myfunction()
{
// Some code here
// ...
// Call MyClass::myfunction() here, but how?
// One way to call the function again.
this->myfunction();
// ...
}
this->mufunction() can be replaced by myfunction(). Use of this is a stylistic option that makes the code easier to read for some, like me.
And, will there be any difference if myfunction() belongs to public: or private:?
No, there won't be. You can call any member function of the class from another member function.

C++ Returning multiple type references from function and casting them to a type that we need

I need a function that returns a variable, but I don't want to specify what type of variable it will return (that's something to be determined in later use).
// unknownType is a char, because it uses only one byte of memory
typedef char unknownType;
unknownType& func (bool typeSelector) {
// let's say we want to return double and int type
double dblVal = 3.5;
int intVal = 5;
// return type depends on typeSelector's state
if (typeSelector == true)
return (unknownType&)dblVal;
else
return (unknownType&)intVal;
}
and then I'll use it like this:
double dblVal = (double&) func(true);
std::cout << dblVal << std::endl;
std::cout << (int&) func(false);
The code above works just fine (if I'm not trying to return more complex object, like std::string for instance, but that's OK for my needs); I've compilated it on either linux and windows. But I'm not convinced if it's a portable solution of my problem.
My question is: is there anything in this code that could break up my program and make it useless? And how efficient is it by the terms of performance?
EDIT: why I can't use templates here
I've got a base class:
class Base {
public:
virtual unknownType& getValue () = 0;
};
And then a couple of derived classes, that are containing different type variables:
class DerivedDbl : public Base {
private:
double value;
public:
DerivedDbl (double val) : value(val) {}
unknownType& getValue () {
double toReturn = value;
return (unknownType&)toReturn;
}
};
class DerivedInt : public Base {
private:
int value;
public:
DerivedInt (int val) : value(val) {}
unknownType& getValue () {
int toReturn = value;
return (unknownType&)toReturn;
}
};
Then I've got a class, that stores derived classes and makes some operations on them:
class Storage {
private:
std::vector <Base*> vec;
public:
void operator+= (Base& obj) { vec.push_back(&obj); }
unknownType& operator[] (int ID) {
return vec[ID]->getValue();
}
};
And I want to be able to get variable values of stored derived classes sometimes (I know which one I've add, so I know their types), but I don't think that creating separate getter methods for each one is not so elegant way to get them, and code like this looks clearer for me:
DerivedDbl derivedDbl(3.5);
DerivedInt derivedInt(5);
Storage storage;
storage += derivedDbl;
storage += derivedInt;
std::cout << (double&)storage[0] << std::endl;
std::cout << (int&)storage[1];
But maybe there's something I've missed and it's possible to do same thing using different methods (I've tried templates and didn't came up with any good ideas, you guys dissuaded void pointers, unions and structures need more memory).
You are returning a reference to a local variable. This may seem to work sometimes, but it is undefined behaviour, and will break your program horribly at some point.
If you really need a virtual function, it should probably return some sort of type hiding class (e.g. boost::any). Then you can cast the returned value to the correct type.
Alternatively you could make the function non-virtual, and cast from the base type to the appropriate derived type. The derived classes could then just return the type you actually want.
Templates could be used to facilitate this behaviour, e.g.:
class Base
{
public:
virtual ~Base() { }
};
template<class T>
class ValueType : public Base
{
public:
explicit ValueType(T value): value(value) { }
T& GetValue()
{
return value;
}
private:
T value;
}
struct Storage
{
std::vector<Base*> objects;
template<class T>
T& GetValue(unsigned int index)
{
auto derived = dynamic_cast<ValueType<T>*>(objects[index]);
return derived->GetValue();
}
};
EDIT: changed access control.

The use case of 'this' pointer in C++

I understand the meaning of 'this', but I can't see the use case of it.
For the following example, I should teach the compiler if the parameter is the same as member variable, and I need this pointer.
#include <iostream>
using namespace std;
class AAA {
int x;
public:
int hello(int x) { this->x = x;}
int hello2(int y) {x = y;} // same as this->x = y
int getx() {return x;}
};
int main()
{
AAA a;
a.hello(10); // x <- 10
cout << a.getx();
a.hello2(20); // x <- 20
cout << a.getx();
}
What would be the use case for 'this' pointer other than this (contrived) example?
Added
Thanks for all the answers. Even though I make orangeoctopus' answer as accepted one, it's just because he got the most vote. I must say that all the answers are pretty useful, and give me better understanding.
Sometimes you want to return yourself from an operator, such as operator=
MyClass& operator=(const MyClass &rhs) {
// assign rhs into myself
return *this;
}
The 'this' pointer is useful if a method of the class needs to pass the instance (this) to another function.
It's useful if you need to pass a pointer to the current object to another function, or return it. The latter is used to allow stringing functions together:
Obj* Obj::addProperty(std::string str) {
// do stuff
return this;
}
obj->addProperty("foo")->addProperty("bar")->addProperty("baz");
In C++ it is not used very often. However, a very common use is for example in Qt, where you create a widget which has the current object as parent. For example, a window creates a button as its child:
QButton *button = new QButton(this);
When passing a reference to an object within one of its methods. For instance:
struct Event
{
EventProducer* source;
};
class SomeContrivedClass : public EventProducer
{
public:
void CreateEvent()
{
Event event;
event.source = this;
EventManager.ProcessEvent(event);
}
};
Besides obtaining a pointer to your own object to pass (or return) to other functions, and resolving that an identifier is a member even if it is hidden by a local variable, there is an really contrived usage to this in template programming. That use is converting a non-dependent name into a dependent name. Templates are verified in two passes, first before actual type substitution and then again after the type substitution.
If you declare a template class that derives from one of its type parameters you need to qualify access to the base class members so that the compiler bypasses the verification in the first pass and leaves the check for the second pass:
template <typename T>
struct test : T {
void f() {
// print(); // 1st pass Error, print is undefined
this->print(); // 1st pass Ok, print is dependent on T
}
};
struct printer {
void print() { std::cout << "print"; }
};
struct painter {
void paint() { std::cout << "paint"; }
};
int main() {
test<printer> t; // Instantiation, 2nd pass verifies that test<printer>::print is callable
t.f();
//test<painter> ouch; // 2nd pass error, test<painter>::print does not exist
}
The important bit is that since test inherits from T all references to this are dependent on the template argument T and as such the compiler assumes that it is correct and leaves the actual verification to the second stage. There are other solutions, like actually qualifying with the type that implements the method, as in:
template <typename T>
struct test2 : T {
void f() {
T::print(); // 1st pass Ok, print is dependent on T
}
};
But this can have the unwanted side effect that the compiler will statically dispatch the call to printer::print regardless of whether printer is a virtual method or not. So with printer::print being declared virtual, if a class derives from test<print> and implements print then that final overrider will be called, while if the same class derived from test2<print> the code would call printer::print.
// assumes printer::print is virtual
struct most_derived1 : test<printer> {
void print() { std::cout << "most derived"; }
};
struct most_derived2 : test2<printer> {
void print() { std::cout << "most derived"; }
};
int main() {
most_derived1 d1;
d1.f(); // "most derived"
most_derived2 d2;
d2.f(); // "print"
}
You can delete a dynamically created object by calling delete this from one of its member functions.
The this pointer is the pointer to the object itself. Consider for example the following method:
class AAA {
int x;
public:
int hello(int x) { some_method(this, x);}
};
void somefunc(AAA* a_p)
{
......
}
class AAA {
int x;
public:
int hello(int x) { this->x = x;}
int hello2(int y) {x = y;} // same as this.x = y
int getx() {return x;}
void DoSomething() { somefunc(this); }
};
this is implicit whenever you use a member function or variable without specifying it. Other than that, there are many, many situations in which you'll want to pass the current object to another function, or as a return value.
So, yeah, it's quite useful.
Sometimes you need to refer to "this" object itself, and sometimes you may need to disambiguate in cases where a local variable or a function parameter shadows a class member:
class Foo {
int i;
Foo* f() {
return this; // return the 'this' pointer
}
void g(){
j(this); // pass the 'this' pointer to some function j
}
void h(int i) {
this->i = i; // need to distinguish between class member 'i' and function parameter 'i'
}
};
The two first cases (f() and g() are the most meaningful cases. The third one could be avoided just by renaming the class member variable, but there's no way around using this in the first two cases.
Another possible use case of this:
#include <iostream>
using namespace std;
class A
{
public:
void foo()
{
cout << "foo() of A\n";
}
};
class B : A
{
public:
void foo()
{
((A *)this)->foo(); // Same as A::foo();
cout << "foo() of B\n";
}
};
int main()
{
B b;
b.foo();
return 0;
}
g++ this.cpp -o this
./this
foo() of A
foo() of B
One more use of this is to prevent crashes if a method is called on a method is called on a NULL pointer (similar to the NULL object pattern):
class Foo
{
public:
void Fn()
{
if (!this)
return;
...
}
};
...
void UseFoo(Foo* something)
{
something->Fn(); // will not crash if Foo == NULL
}
If this is useful or not depends on the context, but I've seen it occasionally and used it myself, too.
self-assignment protection

C++ ...when all the arguments have default values

I guess that this is a very absurd/basic question, but still:
class m
{
public:
void f(int ***);
/***/
}
void m::f(int ***a = NULL)
{
/***/
}
The call to f (as well as any function which has default values for all the arguments) doesn't accept 0 arguments. Why? How should I format the declaration then?
That works fine if the function definition is in the header file. The rule is that whoever is calling the function has to 'see' the default value.
So, I'm guessing you have the function definition in a separate source file. Assuming that's the case, just put the default in the function declaration (in the class):
class m
{
public:
void f(int *** = 0);
/***/
};
You'll also need to remove the default value from the function definition as you can only define the default in a single place (even if the value itself is the same).
This will work:
class m
{
public:
void f(int ***a = NULL);
};
void m::f(int ***a)
{
}
Default values in C++ are syntactic sugar; the compiler essentially inserts the argument for you at the callsite. This means that the compiler needs to know what the default value is, so it must be supplied by the function declaration.
This also means that if you have inheritance and virtual methods, the default values used are the ones from the static type (i.e., what type the compiler thinks the object is), not from the runtime type. For example:
class Base
{
public:
virtual ~Base() { }
virtual std::string foo(std::string s = "b") { return "Base:" + s; }
};
class Derived
: public Base
{
public:
virtual std::string foo(std::string s = "d") { return "Derived:" + s; }
};
int main(void)
{
Derived d;
Base& b = d;
std::cout << b.foo() << std::endl;
return 0;
}
will print Derived:b, not Derived:d.