0

I got an array at the end of my class and i don't know how to use it.

the bus[10] is so hard to understand. I don't know why it can access driver and what does empty() function really do.

#include "conio.h"
#include "stdio.h"
#include "iostream.h"
#include "string.h"
#include "graphics.h"
#include "stdlib.h"
#include "dos.h"
static int p=0;
class a
{
        char driver[10];// driver
    public:
        void install();// for installing

}bus[10];//here we declare the number of buses we can have.
void a::install()
{
    cout<<"Enter bus no: ";//ques
    cin >> bus[p].driver;// what does this mean
    bus[p].empty();//what does this mean
    p++;
}

2 Answers2

3

This is syntax for defining a type, and an instance of that type, at the same time.

For example:

struct Foo {} foo;

is the same as:

struct Foo {};
Foo foo;

So your example defines the type a, and also creates an array of 10 as called bus.

It would be more clearly written thus:

class a
{
   char driver[10];

public:
   void install();
};

a bus[10];

In this manner we can now more easily see that you've created a global array called bus, which you can use like you'd use any other array.

Since p is zero (to begin with), bus[p] just gives you the "first" a object in the array (to begin with). As p is increased, subsequent buses are accessed.

So, this:

cin >> bus[p].driver;

reads into the driver member of the pth bus.*

And this:

bus[p].empty();

means nothing, because a does not have a member function called empty().

* Well, the p+1th bus, because array indices begin at zero but English doesn't!

P.S. You can do funny (read: stupid) things with this syntax!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
-1

This is a very strange looking code, probably from an old workbook. I could help you with achieving the action that you want, but it's hard to understand anything from this snippet.

Wrong: As far as I remember adding a identifier at the end of an unnamed struct gave it a name just like the usual approach.

struct {
    float x, y;
} Point;
//is equal to
struct Point {
    float x, y;
}

However I'm not familiar with the array syntax you provided. I suppose std::cin >> bus[p].driver is meant to read the "name" that the char[10] driver field is. But using a char array here is troublesome and it's much better to replace it with std::string and shortening it to 10 characters after input.

The empty() method is often used as a container function returning boolean and telling the programmer whether the container is empty or not. Here however this function is undeclared and the code won't compile either way.

Not to mention that non-const variables placed out of function scope, like the static int p = 0, are a grave mistake.

Not true: In conclusion this is a very messy code and without the knowledge of what you want to achieve nobody could help you here.

See the answer below for better explanation.

bart-kosmala
  • 931
  • 1
  • 11
  • 20