Sudar
Sudar

Reputation: 20020

Having another class as a class member in C++

I am trying refactor a piece of C++ code into a class. Right now the code looks like this

USB Usb;
ACMAsyncOper AsyncOper;
ACM Acm(&Usb, &AsyncOper);

I want to move this code into the constructor of a class. Also I want to have the variables Usb, AsyncOper and Acm as member variables of the class.

I wrote it as the following

// eZ430.h

class eZ430
{
    public:
        eZ430();    
    private:
        USB Usb;
        ACMAsyncOper AsyncOper;
        ACM Acm;
};


// eZ430.cpp
#include "eZ430.h"

eZ430::eZ430() {
    USB Usb;
    ACMAsyncOper AsyncOper;
    ACM Acm(&Usb, &AsyncOper);
}

But this doesn't seem to work. I am very new to C++ and can't get it to work.

Kindly let me know how to implement it. Thanks.

Edit: When I have the following code in the constructor

eZ430::eZ430() {
    USB Usb;
    ACMAsyncOper AsyncOper;
    ACM Acm(&Usb, &AsyncOper);
}

I get the error error: expected identifier before '&' token

And when I change it to

eZ430::eZ430() {
    USB Usb;
    ACMAsyncOper AsyncOper;
    ACM Acm(&Usb, &AsyncOper);
}

I get the error no matching function for call to 'ACM::ACM()'

Upvotes: 0

Views: 185

Answers (1)

David G
David G

Reputation: 96845

Your constructor should initialize Acm through its member-initializer list:

eZ430() : Acm(&Usb, &AsyncOper)
{}

We do this because ACM doesn't have a default constructor, and we have to make sure that default-construction of eZ430 causes the specialized-construction of Acm.

And leave the body empty as there is no reason to recreate the Usb and AsyncOper data-members inside the constructor. Besides, doing ACM Acm(&Usb, &AsyncOper) potentially causes Undefined Behavior because you're accessing the addresses of local variables that will go out of scope when the constructor body closes. If you use those addresses elsewhere that will cause the Undefined Behavior.

Related: C++ Member Initialization List

Upvotes: 5

Related Questions