Click here to Skip to main content
15,879,348 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, this may be a silly question but is there a way to access a function from a class that has a constructor in it without calling it's constructor? Here is an example:

What I have tried:

class Point {
private:
	int x, y;
public:
	Point()
	{
		x = 1;
		y = 2;
	}
	void callthis() {
		cout << "I want to call this" << endl;
	}
};
Posted
Updated 10-May-18 0:01am

If I understand your question correctly, you can define the function as static and call it without instantiating the class. Have a look at Static Members of a C++ Class[^]
 
Share this answer
 
if you can't change then class, then no, you can't call a member function without instantiating an object (aka calling the constructor).
 
Share this answer
 
The first solution that declaring the function as static is correct, but consider that you than have no object instance on that you can perform the function.

My experience is, that a static function or such problem is only the symptom of some more hidden issues like isnt belonging into this class or the functions isnt optimal at all.

So consider redesigning this class and the function.
 
Share this answer
 
Comments
KarstenK 12-May-18 4:06am    
It is possible. I have seen ending such "utility" classes as mess of unloved stuff. Normally the most important parameter is a hint for the class usage.
As suggested you have to make the method static. That's appropriate for class methods, that is methods independent on a class instance. E.g.
C++
#include <iostream>
using namespace std;

class Point
{
private:
    int x, y;
public:
  Point()
  {
    x = 1;
    y = 2;
  }

  static Point origin()
  {
    Point p;
    p.x = p.y = 0;
    return p;
  }

  void show()
  {
    cout << "{ x = " << x << ", y = " << y << " }" << endl;
  }
};


int main()
{
  Point p;
  p.show();

  p = Point::origin();

  p.show();
}


In the above sample code, the static method origin can be invoked (and, in fact is invoked) without having a Point object reference. On the other hand, the standard (instance) method show is called having a Point object reference.
Note the origin method cannot access any Point instance member.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900