'Is there any in-built function or header file I need to add for Single Inheritance? [duplicate]

This Single Inheritance code has no error but when I run this void the function void B::get_ab() gets executed first as expected, but the line which is second in the function(cin>>a>>b;) gets executed first and then the first line, anyone know whats happening here?

#include<iostream>
#include<stdio.h>

using std::equal_range;
using std::lower_bound;
using std::upper_bound;
using std::pair;
using std::string;
using std::getline;
using std::vector;
using std::cout;
using std::ios;
using std::set;
using std::cin;

class B
{
    int a;
    public: int b;
    void get_ab();
    int get_a(void);
    void show_a(void);
};
class D:private B{
    int c;
    public: void mult();
    void display();
};
void B::get_ab()
{
   
    cout<<"Enter values of a&b";
    cin>>a>>b;
}
int B::get_a()
{
    return a;
}
void B::show_a()
{
    cout<<"a="<<a<<"\n";
}
void D::mult()
{
    get_ab();
    c=b*get_a();
}
void D::display()
{
    show_a();
    cout<<"b="<<b<<"\n"<<"c="<<c<<"\n";
}
int main()
{
   ios::sync_with_stdio(0);
   cin.tie(0);
   D d;
   d.mult();
   d.display();
   return 0;
}```
c++


Solution 1:[1]

The reason for this is that you untied the cin from the cout, in the cin.tie(0);. You can't expect the output to be flushed before the program prompts input from the user.

If you need to preserve this configuration for some reason (i.e. untied streams) and still need the prompt to be printed, you need to flush the output explicitly (e.g. by using either std::flush or std::endl I/O manipulators).

You may want to check this thread: Force std::cout flush print to screen.

And this one: Why do we need to tie std::cin and std::cout

Solution 2:[2]

The execution order is not the problem. Tis is about output buffering and flushing.
You should explcitly flush the prompt output.
You probably do not want the newline there. You can use the explicit flush without newline, i.e.
https://en.cppreference.com/w/cpp/io/manip/flush

Solution 3:[3]

Tanishq. I think the problem may be these two lines of code:

ios::sync_with_stdio(0);
cin.tie(0);

The second line allows stdin and out to operate semi independently by not insuring that buffers from one call have been emptied before another call occurs. I don't think inheritance has anything to do with it. Try commenting them out and seeing what happens.

Why are you using them? There's an excellent discussion of what they do here:

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Yunnosch
Solution 3 Michael H.