Docsity

Class Objects as Members and Initializers in C++, Slides of Computer Science

Partial preview of the text

Download Class Objects as Members and Initializers in C++ and more Slides Computer Science in PDF only on Docsity!

Classes

Class Data Members & Initializers

Class Objects as Members -- Example

  • class student{

char *name;

public:

student(char *ip) {

name = new char[50];

strcpy(name, ip);

~student(){delete[] name;}

Class Objects as Members -- Example

  • class csci_c{ student s1, s2; instructor i1; char *location; public: //Constructor Initializer csci_c(char *n1, char *n2, char *n3, char *l) :s1(n1), s2(n2), i1(n3){ location = new char[50]; strcpy(location, l); } ~csci_c(){delete[] location;} };
  • main() { csci_c fall_class("John","Tom","Henry","SI102");}

Class Objects as Data Members

  • Data Members can be User Defined Types Having

their Constructors

  • Constructor Initializer is Used
  • Appropriate Constructors are Invoked on the

Order they are Specified in the Class Declaration

  • Destructor of the Class Containing Members of

Other Classes is Called First, Followed by the Member's Destructors in Reverse Order of Declaration

Constructor Initializer -- Example

  • /* Assume the Previous Definitions of Classes "student" and "instructor" are Valid */ class csci_c{ student s1, s2; instructor i1; char location; int capacity; public: / Constructor Initializer */ csci_c(char *n1,char *n2,char *n3,char *l,int c) :s1(n1), s2(n2), i1(n3), location(l), capacity(c){} ~csci_c(){} };
  • main() { csci_c summer("John","Tom","Henry","SL110",20); }

Array of Class Objects -- A Class With a Constructor

  • Default Constructor is MUST
  • All the Objects will be Initialized as per the Default Constructor
  • You can use array initializers to pass a single argument to a constructor of a declared array
  • There is NO Way to pass an argument to a constructors of a Dynamic Array Declaration
  • Destructor MUST be Called for EACH ELEMENT in the Array
  • Automatic Array Objects -- Implicit Destruction
  • Explicitly Created Objects by new -- delete[] Operator

Array of Objects -- Example

  • main(){ /* object array of "student" class all initialized to "No Name" – default constructor / student s1[size]; / Initialization -- second constructor / student s2[2] = {"John", "Tom"}; / Dynamically created array -- default constructor */ student s3 = new student[3]; / Dynamically created object -- default constructor */ student s4 = new student; / "s1" and "s2" arrays will be automatically destroyed when "main“ exits. However, array pointed by "s3" and object pointed by "s4", must be deleted. */ delete[] s3; delete s4; }