-1

Hi I'm trying to an array of object of child class in parent class using pointer and trying to initialise the child class variable using functions defined in child class. But it is throwing error that the child object created is not in scope. The code is breaking. Please help me how to do this.

#include<iostream>
using namespace std;
class parent
{
public:    
    int y=0;
    void display(){
    cout<<"Value inside parent of y is "<<y;
    }

};
class child: public parent
{  
public:
    int nop;
    parent *ptr;

    void input()
    {
       int x,nop=0;
       parent p;
       *(ptr+nop) = p;
       cout<<"Enter number";
       cin>>x;
       nop++;
       p.y=x;
       cout<<"Value inside child is "*((ptr+nop)).y;
       p.display();
     }
};

int main(){
child c;
c.input();

return 0;
}


deepanshu
  • 9
  • 4
  • 1
    parent do not have to know child, memorize instances in the constructor of parent. You never initialize *ptr* you cannot dereference it without an undefined behavior – bruno Apr 26 '20 at 10:24
  • Why do you need to have an array of parent object in child class? I think you need to redesign the code. or clarify more what you're doing. – MRazian Apr 26 '20 at 10:49
  • You have changed your question/code significantly. That's not the right way to do that. – abhiarora Apr 26 '20 at 11:15

1 Answers1

1

The problem you have is that you are trying to use the child class before it has been defined. You need to reorganize your code like this

class child;
class parent
{  
public:
    int nop;
    child *ptr;

    void input();
};

class child: public parent
{
public:    
    int y;
};

void Parent::input()
{
   int x,nop=0;
   child c;
   *(ptr+nop) = c;
   cout<<"Enter number";
   cin>>x;
   nop++;
   c.y=x;
   cout<<*(ptr+nop).x;
 }

Now parent::input is defined after class child.

You have lots and lots of other problems in your code, but this should fix one of them and let you make some progress on the others.

john
  • 85,011
  • 4
  • 57
  • 81