Why are you using this? I'm confused
class Myclass
{
public:
void print() const {}
};
If you add the const keyword after the method,
class MyClass
{
private:
int counter;
public:
void Foo(){
counter=0;
std::cout << "Foo" << std::endl;
}
void Foo() const{
//counter = 1; error because the value cannot be changed in //const function
std::cout << "Foo const" << std::endl;
}
};
int main()
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
}
Results are
Foo
Foo const
class MyClass
{
public:
void Foo(){
std::cout << "Foo" << std::endl;
callByFoo();
}
void Foo() const{
std::cout << "Foo const" << std::endl;
The callByFoo(); //const function cannot call non-const methods. error
}
void callByFoo(){
std::cout << "callByFoo" << std::endl;
}
void callByFoo() const
{
std::cout << "callByFoo const" << std::endl;
}
};
int main()
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
}
Results are
Foo
callByFoo
Foo const
callByFoo const
© 2024 OneMinuteCode. All rights reserved.