Inside setMyInt function I have used two statements to set myInt variable. Though both of them gives me the same result. Is there any conceptual difference in working of them?
#include <iostream>
using namespace std;
class Bar{
int myInt;
public:
const int getMyInt() const {
return myInt;
}
void setMyInt(int myInt) {
Bar::myInt = myInt;
this->myInt=myInt;
}
};
int main(){
Bar obj;
obj.setMyInt(5);
cout<<obj.getMyInt();
return 0;
}
You can't really compare them, and they are not interchangeable, but because in C++ you can leave certain things out in certain cases, here it looks like they are.
In fact, both lines are short for:
this->Bar::myInt = myInt;
This means, set the value of the object Bar::myInt (the member called myInt in the scope of the class Bar), which is encapsulated by the object pointed to by this, to the value of the (other) variable myInt.
You can leave out Bar:: because this is a Bar* so that's implicit; you can leave out this-> because you're in a member function so that's implicit too.
More generally, -> performs a pointer dereference and object access, whereas :: is the "scope resolution operator" which fully qualifies a name.
“->” is used as a pointer
“.” Is used for object members variables/ methods
“::” Is used for static variables/ methods or for objects from another scope.
Related
class A
{
public:
A();
void Func1(int,int);
void Func2(long,long);
private:
...
};
<implementation here>
In main:
std::vector<std::function<void(void)>> fl;
A a;
fl.push_back(std::bind(&a.Func1, 1,1));
Gives the error:
ISO C++ forbids taking the address of a bound member function to form a pointer to member function
Solution?
Edit: changed "A a();" to "A a;". No constructor here :P
Edit:
Selected Praetorian's reply as answer because it solves the problem.
Dietmar Kühl's is a good solution too but not the actual answer to the question.
Gotta be fair :D
Func1 is a non-static member function, so it must be invoked on an instance of A, which you'll need to bind as the first argument (the this pointer). Also, when creating a pointer to member function, the syntax is &ClassName::MemFuncName.
So you need
fl.push_back(std::bind(&A::Func1, &a, 1, 1));
Make sure that the lifetime of a does not end before you invoke the bound function.
Two issues. First,
A a();
is a function declaration. You need
A a;
Then,
fl.push_back(std::bind(&A::Func1, &a, 1,1));
You could also just not use std::bind():
std::vector<std::function<void(void)>> fl;
A a{};
fl.push_back([&](){ a.Func1(1, 1); });
The code show references a on the stack. That's OK when the function object doesn't outlive a. If that can't be guaranteed you may want to replace the & by = which would copy the object. BTW, the subtle change from () to {} causes the code to declare a an object of type A rather than as a function taking no argument and returning A.
unfortunately C++ doesn't have a syntax like that. A complete example with the correct syntax would look like this:
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
class A
{
public:
A() {}
void Func1(int,int) {}
void Func2(long,long) {}
};
int main()
{
std::vector<std::function<void(void)>> fl;
A a;
fl.push_back(std::bind(&A::Func1, &a, 1,1));
return 0;
}
You need to provide two things (at least): 1) the pointer to member function 2) the implicit "this" pointer, i.e., the object you want to call the method on.
Then you can add the parameters you want to bind.
Note also that unfortunately you can't make an instance of "A" with "A a();" This is the "most vexing parse". The correct way is "A a;" or "A a{};"
I'm sorry if this question gets reported but I can't seem to easily find a solution online. If I override operator()() what behavior does this define?
The operator() is the function call operator, i.e., you can use an object of the corresponding type as a function object. The second set of parenthesis contains the list of arguments (as usual) which is empty. For example:
struct foo {
int operator()() { return 17; };
};
int main() {
foo f;
return f(); // use object like a function
}
The above example just shows how the operator is declared and called. A realistic use would probably access member variables in the operator. Function object are used in many places in the standard C++ library as customization points. The advantage of using an object rather than a function pointer is that the function object can have data attached to it.
This question already has answers here:
When do I use a dot, arrow, or double colon to refer to members of a class in C++?
(4 answers)
Closed 8 years ago.
Apologies for a question that I assume is extremely basic.
I am having trouble finding out online the difference between the operator :: and . in C++
I have a few years experience with C# and Java, and am familiar with the concept of using . operator for member access.
Could anyone explain when these would be used and what the difference is?
Thanks for your time
The difference is the first is the scope resolution operator and the second is a member access syntax.
So, :: (scope resolution) can be used to access something further in a namespace like a nested class, or to access a static function. The . period operator will simply access any visible member of the class instance you're using it on.
Some examples:
class A {
public:
class B { };
static void foo() {}
void bar() {}
};
//Create instance of nested class B.
A::B myB;
//Call normal function on instance of A.
A a;
a.bar();
//Call the static function on the class (rather than on an instance of the class).
A::foo();
Note that a static function or data member is one that belongs to the class itself, whether or not you have created any instances of that class. So, if I had a static variable in my class, and crated a thousand instances of that class, there's only 1 instance of that static variable still. There would be 1000 instances of any other member that wasn't static though, one per instance of the class.
One more interesting option for when you come to it :) You'll also see:
//Create a pointer to a dynamically allocated A.
A* a = new A();
//Invoke/call bar through the pointer.
a->bar();
//Free the memory!!!
delete a;
Dynamic memory can be a little more confusing if you haven't learned it yet, so I won't go into details. Just wanted you to know that you can access members with { :: or . or -> } :)
in C++ :: is the scope resolution operator. It is used to distinguish namespaces, and static methods, basically any case you don't have an object. Where . is used to access things inside an object.
C# uses the . operator for both of them.
namespace Foo
{
public class Bar
{
public void Method()
{
}
public static void Instance()
{
}
}
}
in C# you would write code like this:
var blah = new Foo.Bar();
blah.Method();
but the equivalent C++ code would look more like this:
Foo::Bar blah;
blah.Method();
But note that the static method would also be accessed using the scope resolution operator, because you're not referencing an object.
Foo::Bar::Instance();
Where again, the C# code would only use the dot operator
Foo.Bar.Instance();
:: is for namespaces and static member access. C# uses the dot-operator for namespaces instead.
. is for non-static member access.
Not an exhaustive delineation, but it's the relevant bits that may confuse you in light of C# and Java.
For further information, see
IBM - Scope Resolution Operator
IBM - Dot Operator
:: is the scope resolution operator, so when you are resolving a scope, such as a namespace or class, you use that. For member access, you have .
The scope operator :: may be hard to understand if you don't understand namespaces or classes. A namespace is like a container for the names of various things in your code. They're generally used to disambiguate names that are common across libraries. Say both namespaces std and example have the function foobar(). So the compiler knows which function you want to use, you prepend it as either std::foobar() or example::foobar().
The :: operator can also be used when telling the compiler you want to define a function declared in a class or structure. For instance:
class foobar()
{
public:
void hello();
int number; //assume there is a constructor that sets this to 5
}
void foobar::hello()
{
cout << "Hello, world!" << endl;
}
The . operator is used when you wish to use a member of a class or structure. For instance:
foobar foo;
foo.hello();
cout << foo.number << endl;
Assuming the class is completed by writing a constructor, the output of this would be expected to be:
Hello, world!
5
You use the . operator the same in java, when accessing members of a class once its created in the program.
the :: is used in number of cases:
When you define a method in the .h/.cpp of a certain class, write
class::methodName()
either for prototyping it, or implementing it.
Also, if you don't explicitly state what namespace you use, you'd have to to use it
std::cout << "This is the output";
instead of just using cout << "This is the output;
Maybe there are more, but i don't remember right now, my C++ is a bit rusty.
In C++, :: is for identifying scope. This can mean namespace scope or class scope.
Eg.
int x;
namespace N {
int x;
struct foo {
static double x;
double y;
};
struct bar: public foo {
double y;
};
}
int main()
{
int x; // we have a local, hiding the global name
x = ::x; // explicitly identify the x in global scope
x += N::x; // explicitly identify the x in namespace N
N::foo::x = x; // set the static member of foo to our local integer
N::foo f;
f.y = f.x; // the static member is implicitly scoped by the object
f.y += N::foo::x; // or explicitly scoped
N::bar b;
assert(b.x == N::foo::x); // this static member is inherited
b.y = b.x; // we get N::bar::y by default
b.N::foo::y = b.y; // explicitly request the hidden inherited one
}
// we need to define the storage for that static somewhere too ...
int N::foo::x (0.0);
Suppose I have a class like:
Class MyClass
{
int myVar1;
int myVar2;
void myMethod();
}
is there any difference in the two value assignments below ?
void MyClass::myMethod()
{
//VARIABLE ASSIGNMENT
myVar1 = 99;
//USING POINTER TO CLASS
this->myVar2 = 99;
}
What's the use of the
this->
pointer in variables' assignment (except other cases when eg. passing the class via a function etc.) ?
It's the same thing, unless you happen to have two variables with the same name in the scope. In that case you can differentiate using this->.
It makes a difference in the following situation:
void MyClass::myMethod(int myVar1)
{
myVar1 = 99; //doesn't change the member
this->myVar1 = 99; //changes the member
}
In your case, no difference.
There is no difference. Sometimes using this-> aids in disambiguation, but not here.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have some questions about C++ from a C# developer.
For a few days I have been looking at some C++ code, and I have the following questions:
When do use Foo::, Foo. and Foo-> ?
When do I use a real constructor and when just String a; (sometimes I need to do something like String a("foo");)
What is the difference between these signatures: int foo(int a) and int foo(int &a)?
:: is used either to explicitly specify a namespace (std::string, for example, for the string class in the namespace std), or for static members of a class.
. is used much as in C#, to refer to a member of a class.
-> is used with pointers. If p is a pointer to an object obj, then p->x has the same meaning as obj.x.
when do i use a real constructor and when just String a; (sometimes i need to do something like String a("foo");)
When you need to. String a is roughly equivalent to C#'s a = new String() (with the caveat that if String is a non-POD type, it may contain uninitialized members.)
If you need a initialized to a specific value, you do that. (either with String a("foo"), or with String a = "foo")
where is the difference between these signatures: int foo(int a) and int foo(int &a)?
The & denotes a reference. It's not quite a C# reference, but there are similarities. In C#, you have value types and reference types, and reference types are always passed by reference.
In C++, there's no such distinction. Every type can be passed by value or by reference. The type T& is a reference to T. In other words, given the following code:
void foo(int& j);
void bar(int j);
int i = 42;
foo(i);
bar(i);
foo will get a reference to i, which means it it can modify the value of i.
bar will get a copy of i, which means that any modifications it makes will not be reflected in i.
You often use const T& (a reference to const T) as a way to avoid the copy, while still preventing the callee from modifying the object.
1: Assuming you which to call a method
Foo::theMethod(...)
is for example used when calling a static method of a class Foo
Foo.theMethod(...)
is when you have an object named Foo
Foo->theMethod(...)
is when you have a pointer to a object of named Foo
2:
String a;
calls the default constructor that takes no arguments
String a("foo")
calls a overloaded constructor
3:
int foo(int &a)
takes a reference to an integer, so within the method you are able to manipulate a.
int foo(int a)
makes a copy, manipulating it wont have any effect of the actual parameter passed in after leaving the method.
Question 1:
It depends on what Foo is. The :: operator is called the scope
resolution operator; the operand on the right must be a namespace or a
class, and the operand to the left a member of the namespace or class.
If Foo is a class, Foo:: can be used to access a static member, or
from within a member of a derived class, to access the member of the
base class: e.g.:
class Foo
{
public:
virtual void f();
static void g();
};
int h()
{
Foo::g();
}
class Derived : public Foo
{
public:
virtual void f()
{
Foo::f(); // Call function in base class...
}
}
It's often used to access namespace members as well, e.g. std::cout
(the cout object in namespace std).
The . operator is a member access operator, and requires an object (or
a reference to an object) as the left hand operand. Thus (using the
above definitions):
Foo obj;
obj.f();
void i( Foo& rFoo )
{
rFoo.f();
}
It can also be used to access static members, if you have an instance:
Foo obj;
obj.g();
The -> is very much like the . operator, except that it takes a
pointer to an instance, rather than an instance, and (very importantly)
it can be overloaded. Thus:
Foo* obj;
obj->g();
// And if Ptr is a user defined type with an overloaded
// `operator->` which returns a Foo*
Ptr obj;
obj->g();
Again, you can also use this syntax to access a static member, if you
have a pointer to an object.
Question 2:
The definition String a; calls a real constructor. You use String
a; when you want the default constructor; the one with no parameters.
You use String a( "foo" ); when you want the constructor which takes a
char const* (or a char const (&)[4], but that's highly unlikely, since it
will only work for a string literal with exactly three characters).
In general, when defining variables:
String a; // default constructor...
String a1(); // NOT what it looks like: this is a
// function declaration, and not the
// definition of a variable!!!
String b( x, y, z ); // constructor taking x, y and z as arguments...
String c = x; // implicitly convert `x` to String, then
// copy constructor.
The last form is a bit tricky, since the copy constructor may be (and
almost always is) elided, but the legality of the program is defined by
the rule above: there must be a way of implicitly converting x into a
String, and String must have an accessible copy constructor.
In other contexts, e.g. new String(), the form with empty parameters
can be used for "value construction", which is the default constructor
if there is a user defined one, otherwise zero initialization.
Question 3:
The first is pass by value, and passes a copy of the argument to the
function. The second is pass by reference, and passes a reference
(which behaves sort of like a hidden, automatically dereferenced
pointer) to the function. Thus:
void f( int a )
{
++ a; // Modifies local copy, has no effect on the argument.
}
void g( int& a )
{
++ a; // Modifies the variable passed as an argument.
}
Note that in the first case, you can pass an arbitrary expression; in
the second, you must pass something called an lvalue—that is,
something you can access afterwards using a similar expression (a named
variable, or a dererenced pointer, or an element in a named array,
etc.).
String a : construct an empty String object
String a("foo") : construct a String object initalized to "foo"
int foo(int a) : pass a by value/copy to foo. Inside foo if you modify a , a will not be impacted outside foo
int foo(int& a) : pass a by reference inside foo. If you modify a , a will also be modify once foo ended
Foo:: - Static methods
Foo. - Instance Methods when you have a stack object instance. (MyObject obj)
Foo-> - Instance methods when you have a object pointer. (MyObject* pObj = new MyObject())
Whenever you need to pass some value to the constructor.
int& is a reference to an int. Any changes to a within the method will affect a outside the method. (Equivalent to ref in C#)