-1

I came through a pretty interesting question... what can be the class declaration for the following segment of code in c++..

int main(){    
    Point f(3,4);        //class Point    
    f(4);    
}

the object declaration can be done by declaring a constructor f(int, int). But how can we use a constructor declaration to assign values to an object?? Even if define another constructor f(int), this will not work... as constructors are called only during object declaration. Please suggest a way to do this....

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220

3 Answers3

3

You can use assignment operator:

Point f(3, 4);
f = Point(4);
Daniel
  • 30,896
  • 18
  • 85
  • 139
2
class Point
{
public:
    Point(int,int);
    void operator()(int);
};

It is, of course, not a constructor in this case. But that's how the syntax you showed could be legal.

Here's some more information about operator(): Why override operator()?

Community
  • 1
  • 1
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
0

what can be the class declaration for the [above] segment of code in c++..

The obvious class declaration includes operator()(int). A less obvious class declaration follows:

class Point {
typedef void (*FunPtr)(int);
public:
  Point(int, int) {}
  static void Fun(int) {}
  operator FunPtr() { return Fun; }
};
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • How will this do the required? Static functions can't access concrete object data. – SomeWittyUsername Oct 27 '12 at 18:08
  • @icepack: I don't believe that's a requirement. I believe that the OP is just confused about some syntax he saw. He mistakenly thought that it was calling a constructor, and that misunderstanding is what informed the odd wording in the rest of his question. – Benjamin Lindley Oct 27 '12 at 18:28
  • Right -- the first sentence of the question is the brain-teaser. The rest of it is OP's thinking about how to solve it. – Robᵩ Oct 27 '12 at 18:48