2

I have below scenario in c++ within DEV c++

class base{
    int i=0;
    public:
         base(){
            cout<<"base default constructor"<<endl;
         }
         base(int i){
             cout<<"base with int"<<endl;
         }
};

class derive : public base{
    int j;
    public:
        derive(){
            cout<<"derive default";
        }
        derive(int i){
            int k=5;
            base(k);//////error 
            cout<<"derived with int "<<i<<endl;
        }
        void fun(int i){
            cout<<"finction "<<i<<endl;
        }
};
int main()
{
    derive d(9);

}

After running following error is coming
[Error] conflicting declaration 'base k'
[Error] 'k' has a previous declaration as 'int k'
Why this error is coming.
Its working fine when i call base(5) with any parameter except declared in derived constructor.
Thanks in advance.

Ryuk
  • 21
  • 3

4 Answers4

1

If you call the base constructor within the derived class on the implicit parameter, it needs to be done in the field initialization list like so:

    derive(int i) : base(i) {
        cout<<"derived with int "<< i <<endl;
    }

live demo

Community
  • 1
  • 1
scohe001
  • 15,110
  • 2
  • 31
  • 51
0
#include <iostream>

using namespace std;

class base{
public:
    base(){
        cout<<"base default constructor"<<endl;
    }
    base(int i){
        cout<<"base with int "<<i<<endl;
    }
};

class derive : public base{

public:
    int j;
    int k;
    derive(){
        cout<<"derive default\n";
    }
    derive(int i){
        k=5;
        base(this->k);//////error
        cout<<"derived with int "<<i<<endl;
    }
    void fun(int i){
        cout<<"finction "<<i<<endl;
    }
};
int main()
{
    derive p(10);


}
0

There are two interpretations of what base(k) could be:

  1. it could be a the creation of temporary
  2. it could be a variable declaration: the variable name can be in parenthesis

Out of these two choices, the compiler uses the second one: if something can be either a declaration or an expression, the declaration is chosen. This is related to the most vexing parse although it isn't that. The effect is that in your use base(k); tries to define a variable named k of type base.

You can disambiguate the meaning using one of

  1. (base(k));
  2. base{k};

If base also had a constructor taking an std::initializer_list<int> these two can have different meanings.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
-1

In main()

    base b(3);
    derive d(9);
    base b1(2);

//create explicit object and pass integer parameter.then try also pass particular integer value in derive->base. in derive

base(8);

And always print the value of variable acting weirdly in a program

RajkumarG
  • 146
  • 13