devxlogo

Call a Private Method of a Class

Use this polymorphic technique to cheat the compiler and expose private information:

See the code below.class A{public:	virtual void f2()	{		printf("in A::f2
");	}};class B: public A{private:	void f2(int j)	{		printf("in B::f2
");	}	};int main(){	B b;	A *a = &b;	a->f2(10);	}

Because a->f2 is virtual and called run time, using it calls f2 of B. F2 is private in B, but still you’re still able to call it. That’s the magic.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.