Struct

Introduction

C++ supports a second keyword, struct that can be used to define class types. The struct keyword is inherited from C.

Difference between structs and classes
The only difference between structs and classes in C++ is that the members of a struct have public visibility by default, and the members of a class have private visibility by default.

If we define a class using the class keyword, then any members defined before the first access label are implicitly private; if we use the struct keyword, then those members are public. Whether we define a class using the class keyword or the struct keyword affects only the default initial access level.

We could have defined our Sales_item equivalently by writing

Example

struct Sales_item 
{
     // no need for public label, members are public by default
    // operations on Sales_item objects
     private:
         std::string isbn;
         unsigned units_sold;
         double revenue;
 };

There are only two differences between this class definition and our initial class definition: Here we use the struct keyword, and we eliminate the use of public keyword immediately following the opening curly brace. Members of a struct are public, unless otherwise specified, so there is no need for the public label.

Pointers to Structures

More about pointers.

Structures can be pointed by its own type of pointers.

Example

// pointers to structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
 
struct movies_t 
{
  string title;
  int year;
};
 
int main ()
{
  string mystr;
 
  movies_t amovie;
  movies_t * pmovie;
  pmovie = &amovie;
 
  cout << "Enter title: ";
  //pmovie->title is the same as (*pmovie).title
  getline (cin, pmovie->title);
  cout << "Enter year: ";
  getline (cin, mystr);
  (stringstream) mystr >> pmovie->year;
 
  cout << "\nYou have entered:\n";
  cout << pmovie->title;
  cout << " (" << pmovie->year << ")\n";
 
  return 0;
}

Nesting structures

Example

struct movies_t 
{
  string title;
  int year;
};
 
struct friends_t 
{
  string name;
  string email;
  movies_t favorite_movie;
} charlie, maria;
 
friends_t * pfriends = &charlie;

Member Functions in structs

Example

using std::cout;
using std::cin;
using std::endl;
 
struct person_str
{
  string name;
  int age;
 
  //constructor
  person_str()
  {
        name = "default";
        age = 77;
 }
 
  void print();
};
 
void person_str::print()
{
    /* 
      we don't have to mention what "name" and "age" are,
         because it automatically refers back to the
         member variables.
         The "this" variable is the implied first argument,
         which is a pointer to the object that the member it was called on.
     */
    cout << name << " " << this->age << endl;    
}
 
int main()
{
    person_str p1;
    p1.name = "Chrys";
    p1.age = 26;
 
    p1.print(); 
}

Using typedef

Example

#include <iostream>
#include <string>
using namespace std;
 
typedef struct dataElement 
{
   string SVal;
   int    iVal;
   bool   hasData;
 
   dataElement()   // Example of a constructor used in a structure.
      : iVal(-1), hasData(0)
   {}
} DataElement;
 
main()
{
    DataElement *RealData;
    RealData = new DataElement [ 5 ];
 
    RealData[0].SVal = "Value loaded into first structure element.";
    RealData[0].hasData = 1; // True
 
    cout << "First element  0: " << RealData[0].SVal << endl;
    cout << "                  " << RealData[0].hasData << endl;
    cout << "Second element 1: " << RealData[1].SVal << endl;
    cout << "                  " << RealData[1].hasData << endl; // Show effect of contructor
    cout << "                  " << RealData[1].iVal    << endl; // Show effect of contructor
 
    delete [] RealData;   // Or:  delete [5] RealData;
}

Structures as Function Parameters

You can pass structures across as function parameters pretty easily. The type of the parameter is the same as the name of the structure type.

Example
This is a function that displays the details for a person.

#include <iostream>
#include <string>
 
using std::string;
using std::cout;
using std::cin;
using std::endl;
 
struct person
{ string name;
    int eye_colour;
    float height;
};
 
void display_details(person someone);
 
int main()
{
    person me;
 
    me.name = "Chrys";
    me.eye_colour = 2;
    me.height=1.90;
 
    display_details(me);
 
}
 
void display_details(person someone)
{
    cout << "Name : " << someone_I_know.name << endl;
        cout << "Eye colour : ";
        switch (someone_I_know.eye_colour)
        { 
        case 1 : cout << "Brown";  break;
               case 2 : cout << "Blue";   break;
               case 3 : cout << "Green";  break;
               default : cout << "Unknown";
         }
 
    cout << endl;
        cout << "Height : " << someone_I_know.height
         << " metres" << endl;
}

Member Functions in Structures

Example
A function which is linked to a structure like this is called a member function of that structure.

struct rectangle
{ 
  double length, width;
  double area()
 { 
    return length * width;
 }
 double perimeter()
 { 
    return 2 * (length + width);
 }
};

Template Structures

C++ allows structures to be declared as templates. In other words, constituent members of a structure do not necessarily come from a specific type.

Example

The following structure stores two variables of a user-specific type and has an overloaded plus operator.

template <class A, class B> struct twothings 
{
    A one;
    B two;
    twothings operator+ (const twothings &arg) const 
    {
       twothings <A, B> temp;
       temp.one = one + arg.one;
       temp.two = two + arg.two;
       return temp;
    }
};
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.