0

I have a class A which is in a separate file(sayfile1.cpp)

class A{
public:
      virtual int add(){
      int a=5;
      int b=4;
      int c = a+b;
      return c;
      }
};

Now in a different file(say file2.cpp), i have a function(i have a many other things in this function) inside which i want to create a class inherited from class A and implement the virtual method declared in class A.

void function(Mat param1, Mat param2)
{
  //Some process here..
  ..
  ..
  int c=100;
  class B:public A{
  public:
        virtual int add(){

        return c;
        }
  };

}

Now if i were to call the function int add(), i want the result of c to be 100 and not 9.

Is it possible to do something like this in C++ ??

Thanks in advance

2 Answers 2

1

Define member variable:

class B: public A {
    int c_;
public:
    explicit B(int c):c_(c){};
    virtual int add() {
        return c_;
    }
}
B variable((100));
2
  • wat is the 'variable' u used ? i am tring to implement the same logic for a return type of IplImage* for Opencv and i am facing problems with this'variable' term i am new to c++. so please bear with me.
    – viggie
    Dec 21, 2012 at 13:27
  • When i use this logic for IplImage* instead of int, i get this error- "Object of abstract class type “B” is not allowed". Any suggestions to ovecome this error ?
    – viggie
    Dec 21, 2012 at 14:28
0

You need to split your file1.cpp into file1.h:

#ifndef FILE1_H
class A {
public:
  virtual int add();
};
#endif

and file1.cpp with it's implementation:

int A::add { /*your code * }

In the other file you include only the header file:

#include "file1.h"

The following is not legal in C++:

void function(Mat param1, Mat param2)
{
  //Some process here..
  ..
  ..
  int c=100;
  class B:public A {
  public:
    virtual int add(){

    return c;
    }
 };

}

Instead, you need something like this:

class B : public A {
public:
    B(int v) : c(v) {}
    virtual int add(){ return c; }
private:
    int c;
};

void function(Mat param1, Mat param2)
{
  //Some process here..
  ..
  ..
  int c=100;
  B o(c);

}

2
  • thank you for the quick reply. I do not understand everything here but when i tried debugging, the code went from B o(c) to class B : public A { public: ->B(int v) : c(v) {} virtual int add(){ return c; } private: int c; }; and then it breaks out of the loop. I wanted the value of c to be passed to virtual int add() function defined in the next step
    – viggie
    Dec 21, 2012 at 12:25
  • i am sorry. this i am new to this community and i don know how to type these comments in an organized way! i meant the code went to B(int v) : c(v) {} and went out of the class to line after B o(c)
    – viggie
    Dec 21, 2012 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.