0

I have a problem described as below ::

    class datad {
    private:
        int *a;
        int _size;
        vector<int> v;

    public:
        datad(int arr[], int size) {
            _size = size;
            for (int i = 0; i < size; i++)
                a[i] = arr[i];
        }
        datad(vector<int> ve)
        {
            v = ve;
            _size = ve.size();
        }

        void printdata()
        {
             // print data which the object has been initialized with
             // if object is initialized with vector then print vector
             // array print array
        }
    };

   int main()
   {
        // print only vector data
    int a[] = { 9,4,8,3,1,6,5 };
    datad d(v1);
    d.printdata();

    // print only array data

    datad d1(a, 7);
    d1.printdata();
 }

I need to find the way the object is initialized and then based on the same should be able to printdata accrodingly. Can someone help me understand if it is possible at all?

2 Answers2

3

Add a bool usesVector to your class and set it to true or false in each constructor as appropriate. Then, in printdata, simply check the value of the boolean.

Or you can set size to -1 in the vector case (as it's otherwise unused) and just check for that.

By the way, your array implementation is broken, because you never allocate any memory for it. You'd be much better off using only the vector version. You can still initialise that vector from array data if you wish.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    +1 for "using only the vector version" No sense of keeping that dangerous int* around when you have access to the stl. – DeathTails May 06 '16 at 14:23
  • I accept your solution, but my point is to find out a way to what the object has been initialized with. This is just an example to put my point. –  May 06 '16 at 14:32
  • Logically im expecting there should be more powers to an object to understand its state or how its been initialized. Looks like it has very little practical application in C++. Anyways thank you dear. –  May 06 '16 at 14:52
  • @raghureddy: What constitutes the state of an object is determined by the person who writes the class. That's you. You can accomplish it in the manner I explained in my answer. – Lightness Races in Orbit May 06 '16 at 15:21
1

You can set a flag in respective constructor and check that flag during the printing method.

I hope this is for learning purposes, otherwise as noted you maybe better of using just the vector version. When using dynamic memory management in class you need to be aware of things like rule of three and I guess there is also rule of five.

Community
  • 1
  • 1
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90