Ahmed Nabil
Ahmed Nabil

Reputation: 101

two separate classes doesn't share the same data c++

I have two different classes PipeNetwork.hpp PipeNetwork.cpp and Tube.hpp Tube.cpp

which class Tube : public PipeNetwork

the following function in PipeNetwork

void PipeNetwork::testing()
    {
        Tube u;
        u.length();
        std::cout << "function works fine" << std::endl;
    }

length() is functions located in Tube

void Tube::length()
    {
        std::vector<double>::iterator i;
        L.reserve(get_tubes_numbers());        // get_tubes numbers is function in PipeNetwork

            //bla bla bla
    }
int PipeNetwork::get_tubes_numbers()
    { 
        return tubes_numbers;
    }

and finally at main

int main()
{
   PipeNetwork Oral;
   Oral.InputData("Input.txt");
   Oral.testing();
   return 0;
}

what should happen:

1- InputData take some data and storing it in PipeNetwork class including get_tubes_numbers() which done fine

2- testing should get get_tubes_numbers() from PipeNetwork and preform calculation in Tube class

but the problem is get_tubes_numbers() alwayes return empty with 0 value

and according to my understanding, it's because object u is created separately from object Oral as shown in the image what objects look like in visual studio 01 02

but Tube u; should be a subclass and subclass should share the same variables from the base class Or my understanding of the subclass is wrong? correct me, please.

how to solve this problem?

And thank you for your time

Upvotes: 1

Views: 91

Answers (1)

Zig Razor
Zig Razor

Reputation: 3495

The error is in the testing class. You create a new object u that is initialized with default constructor. This cause your program to have all member of the class standard initialization. So get_tubes_numbers() return 0 because tubes_numbers variable is initialized to 0.

To solve this you can declare a constructor with parameters. In this case the best choice is to pass as parameter the base class PipeNetwork and initialize in the constructor the field you need.

This is an example of constructor you can implement:

Tube::Tube(PipeNetwork& base)
    {
        this->tubes_numbers = base.tubes_numbers;
    } 

then you can just modify the code like this:

void PipeNetwork::testing()
    {
        Tube u(*this);
        u.length();
        std::cout << "function works fine" << std::endl;
    }

Upvotes: 2

Related Questions