Is there any way to call some function on a class without the constructor was called ?

Jul 14, 2011 at 8:42am
I'd like to call some function on a class without create it
(I dont want to use the code placed at the constructor )
Any idea ?
Jul 14, 2011 at 8:57am
make it a static class
Jul 14, 2011 at 10:21am
closed account (z05DSL3A)
What is the function to do? Scratch that, if the function operates on the class and not an instance object of the class, then make the function static.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
#include <sstream>
using namespace std;


class X 
{
private:
  int i;
  static int si;
public:
  void set_i(int arg) { i = arg; }
  static void set_si(int arg) { si = arg; }

  void print_i() {
    cout << "Value of i = " << i << endl;
    cout << "Again, value of i = " << this->i << endl;
  }

  static void print_si() {
    cout << "Value of si = " << si << endl;

  }

};

int X::si = 77;       // Initialize static data member

int main() 
{
  X xobj;
  xobj.set_i(11);
  xobj.print_i();

  // static data members and functions belong to the class and
  // can be accessed without using an object of class X
  X::print_si();
  X::set_si(22);
  X::print_si();
}
Code from IBM site
Last edited on Jul 14, 2011 at 10:29am
Jul 14, 2011 at 11:57am
Thanks.
Topic archived. No new replies allowed.