Reputation: 39
I am a new C++ user...
I have a question regarding how to declare a member of a class "classA" that is an object of another class "classB", knowing that "classB" has a constructor that takes a string parameter (in addition to the default contructor). I did some research online about this issue however it did not help much to help me fix the issue I'm dealing with.
To be more specific, I want to create a class that has as member a VideoCapture object (VideoCapture is an openCV class that provide a video stream).
My class has this prototype :
class myClass {
private:
string videoFileName ;
public:
myClass() ;
~myClass() ;
myClass (string videoFileName) ;
// this constructor will be used to initialize myCapture and does other
// things
VideoCapture myCapture (string videoFileName /* : I am not sur what to put here */ ) ;
};
the constructor is :
myClass::myClass (string videoFileName){
VideoCapture myCapture(videoFileName) ;
// here I am trying to initialize myClass' member myCapture BUT
// the combination of this line and the line that declares this
// member in the class' prototype is redundant and causes errors...
// the constructor does other things here... that are ok...
}
I did my best to expose my issue in the simplest way, but I'm not sure I managed to...
Thank you for your help and answers.
L.
Upvotes: 0
Views: 565
Reputation: 674
If you want a VideoCapture to be a member of the class, you don't want this in your class definition:
VideoCapture myCapture (string videoFileName /* : I am not sur what to put here */ ) ;
Instead you want this:
VideoCapture myCapture;
Then, your constructor can do this:
myClass::myClass (string PLEASE_GIVE_ME_A_BETTER_NAME)
: myCapture(PLEASE_GIVE_ME_A_BETTER_NAME),
videoFileName(PLEASE_GIVE_ME_A_BETTER_NAME)
{
}
Upvotes: 1
Reputation: 70989
What you need is initializer list:
myClass::myClass (string videoFileName) : myCapture(videoFileName) {
}
This will construct myCapture
using its constructor that takes a string
argument.
Upvotes: 2