+ 2
It seems there is a way to bypass the private tag...how can that happen?
#include<iostream> using namespace std; class A{ public: virtual void f()=0; }; class B: public A { private: void f(){cout<<2;} }; void c(A &a){a.f();} //The output is 2. //void c(B &a){a.f();} /*when de-commenting this sentence, an error happens saying f() is private, which means objects in class A can call private functions in B, but objects in class B itself can't? */ int main(){ B b; c(b); }
2 ответов
+ 1
C++ does a lot of type checking but it has its limits. A virtual function should have a similar purpose for each of their definitions so they should either be both private or both public. The code above is somewhat like this:
const int a = 5;
const int* ptr1 = &a;
unsigned long b = (unsigned long)(ptr1);
int* ptr2 = (int*)(b);
*ptr2 = 10;
there are many ways to bypass type checking intentionally or by accident but with virtual functions, each definition should all have the same purpose else they should be separate functions. For example, something like controlling a mob's movement in a game through a function called handle_movement() should be virtual:
/*it's been a while since ive written code so pardon me for any slight syntax errors but the main idea should be clear*/
class Mob{
public:
virtual void handle_movement() = 0;
};
class Slime: public Mob{
public:
virtual void handle_movement(){/*what a slime does...*/}
};
class Mushroom: public Mob{
public:
virtual void handle_movement(){/*what a mushroom does...*/}
};
0
Thanks for your answer. Your analogy appeals me a lot which I think is impressive, but a new question appears: when I execute the code you've mentioned, it seems the value of "a" doesn't change while the value of "*ptr1" does change. It seems the value of "a" is saved somewhere else. How does that happen?
#include <iostream>
using namespace std;
int main()
{
const int a=5;
const int* ptr1=&a;
unsigned long b=(unsigned long)(ptr1);
cout<<b<<endl<<ptr1<<endl;//6422280==0x61ff08
int* ptr2=(int*)(b);
*ptr2=10;
cout<<a<<endl<<*ptr1<<endl<<*ptr2<<endl;
cout<<&a<<endl<<ptr1<<endl<<ptr2<<endl;
}
/*output
6422280
0x61ff08
5
10
10
0x61ff08
0x61ff08
0x61ff08
*/