use struct to initialize a class : Struct Class « Class « C++






use struct to initialize a class

   
#include <iostream>
#include <string.h>
using namespace std;
struct BookInfo {
  char title[64];
  char publisher[64];
  char author[64];
  float price;
  int pages;
};

class BookStuff {
  public:
    BookStuff(char *title, char *publisher, char *author);
    BookStuff(struct BookInfo);
    void show_book(void) 
  { cout << "Book: " << title << " by " <<
        author << endl << "Publisher: " << publisher << endl; };
  private:
    char title[64];
    char author[64];
    char publisher[64];
};

BookStuff::BookStuff(char *title, char *publisher, char *author)
 {
   strcpy(BookStuff::title, title);
   strcpy(BookStuff::publisher, publisher);
   strcpy(BookStuff::author, author);
 }

BookStuff::BookStuff(BookInfo book)
{
   strcpy(BookStuff::title, book.title);
   strcpy(BookStuff::publisher, book.publisher);
   strcpy(BookStuff::author, book.author);
}

int main(void)
{
   BookInfo book = {"T", "J", "a", 29.95, 256 };

   BookStuff big_book("C", "P","K");
   BookStuff little_book(book);

   big_book.show_book();
   little_book.show_book();
}
  
    
    
  








Related examples in the same category

1.Constructor and destructor inside a structConstructor and destructor inside a struct
2.Stack class using a structure.Stack class using a structure.
3.Using a structure to define a class.Using a structure to define a class.
4.Classes and Structures are Related
5.Using a class instead of struct.
6.add method to struct