Home > Enterprise >  C Inherited class function not working in class constructor, pass by reference string not changing
C Inherited class function not working in class constructor, pass by reference string not changing

Time:03-28

I have a class named Filesys inheriting a class Sdisk

class Sdisk
{
    public:
    Sdisk(string disk_name, int number_of_blocks, int block_size);
    Sdisk(); //default constructor
    ...
    int getblock(int blocknumber, string& buffer); //buffer is changed but doesn't change when called by Filesys constructor

    private:
    string diskname;    //file name of software-disk
    int numberofblocks; //number of blocks on disk
    int blocksize;  //block size in bytes

};

class Filesys: public Sdisk
{
    public:
    Filesys(string disk_name, int number_of_blocks, int block_size);
    Filesys(); //default constructor
};

My constructor for Fileys is calling getblock from the Sdisk class and returns the correct value, but my string buffer does not change

Filesys::Filesys(string disk_name, int number_of_blocks, int block_size) {
    string buffer;
    int code = getblock(0, buffer);

    if (code == 0) {  //passes this so it is calling the function and returning a value
        cout << "Failed"; 
    }

    cout << buffer; //empty, buffer is not being changed by getblock
}
//returns the blocknumber called for and passes it by ref in buffer
int Sdisk::getblock(int blocknumber, string &buffer){
    ifstream file(diskname);
    int i = (blocknumber -1) * blocksize;
    int j = (blocknumber * blocksize) -1;
    int k = 0;
    char b;

    if (j > (blocksize * numberofblocks)) {
        file.close();
        return 0;
    }

    while (file >> noskipws >> b) {
        if ((k > i-1) && (k < j 1)) {
            buffer.push_back(b);
        }
        k  ;
    }
    file.close();
    return 1;

}

This function works when it is called normally like

Sdisk disk1("test1",16,32);
string block3;
disk1.getblock(4, block3);
cout << block3; //correctly outputs what is being asked

Why might this be happening?

CodePudding user response:

The ctor of Filesys should forward the parameters to the base class ctor. Something like:

Filesys::Filesys(string disk_name, int number_of_blocks, int block_size) 
    : Sdisk(disk_name, number_of_blocks, block_size) 
{
    // ...
}

Otherwise the members of the base class (e.g. diskname) are not initialized properly, and they are needed for Sdisk::getblock to run properly.

CodePudding user response:

Your function getBlock is called with blockNumber == 0

so these values will be weird.

int i = (blocknumber -1) * blocksize;
int j = (blocknumber * blocksize) -1;

i == -blocksize
j == -1

Then in your while loop, k will never be smaller than 0 (j 1)

if ((k > i-1) && (k < j 1)) {
   buffer.push_back(b);
}
k  ;
  •  Tags:  
  • c
  • Related