Home > front end >  how to pass pointer to constructor in c
how to pass pointer to constructor in c

Time:02-08

have a derived class that needs to take a pointer as a constructor for the base class.

how do you do this in c , i tried it but it gave me a bug.

#include <iostream>

using namespace std;

class Base {
protected:
    int *num;
public:
    Base(int *num);
    virtual void print();
};

Base::Base(int *num){
    this->num = num;
};

class Derived : public Base {
public:
    Derived(int *num) : Base(*num);
    void print();
};

Derived::print(){
    cout << "int value : " << *(this->num);
};

int main(){
    int num = 5;
    int *p = &num;
    
    Derived derived(p);
    derived.print();

    return 0;
}

CodePudding user response:

In the constructor initializer list of Derived you have to write Base(num) instead of Base(*num) as shown below:

Derived(int *num): Base(num) 
{
   //code here
}

Note that you don't have to dereference the pointer num which you were doing while using it in the constructor initializer list. When you dereference num, you got an int. And so you were passing that int to the Base constructor.

  •  Tags:  
  • Related