Download presentation
Presentation is loading. Please wait.
1
Dynamic Memory Allocation
float *thingPtr = new float( ); // the variable pointed by thingPtr becomes class Student { public: Student( char *pName=“no name”, int xfrHours=0, float xfrGPA=0.0 ) { // defined as before } private: char name[40]; int semesterHours; float gpa; }; Student *ptrStudent1, *ptrStudent2; ptrStudent1 = new Student; ptrStudent2 = new Student( , 3, 3.5 ); delete ptrStudent1; delete ptrStudent2; ptrStudent1 = new Student[100]; delete[] ptrStudent1;
2
Static class member—a data member owned by a whole class as
Opposed to by an individual class instance #include <iostream.h> #include <string.h> class Employee { public: Employee( const char*, const char* ); ~Employee(); const char *getFirstName() const; const char *getLastName() const; static int getCount(); // only have access to static members private: char *firstName; char *lastName; static int count; // belongs to the entire class instead of a particular object };
3
int Employee::count=0;
int Employee::getCount() { return count; } Employee::Employee( const char *first, const char *last ) { firstName = new char[strlen(first)+1]; strcpy( firstName, first ); lastName = new char[strlen(last)+1]; strcpy( lastName, last ); ++count; cout<<“Employee constructor for “<<firstName <<‘ ‘<<lastName<<“ called.”<<endl; } Employee::~Employee() { cout<<“~Employee() called for “<<firstName<<‘ ‘<<lastName<<endl; delete[] firstName; delete[] lastName; --count;
4
const char *Employee::getFirstName() const
{ return firstName; } const char *Employee::getLastName() const { return lastName; void main() { cout<<“Number of employees before instantiation is “ <<Employee::getCount()<<endl; Employee *e1Ptr = new Employee( “Susan”, “Baker” ); Employee *e2Ptr = new Employee( “Robert”, “Jones” ); cout<<“Number of employees after instantiation is “<<e1Ptr->getCount(); cout<<“\n\nEmployee 1: “<<e1Ptr->getFirstName() <<“ “<<e1Ptr->getLastName()<<“\nEmployee 2: “ <<e2Ptr->getFirstName()<<“\n\n”; delete e1Ptr; delete e2Ptr; cout<<“Number of employees after deletion is “
5
#include <iostream.h>
class Implementation { public: Implementation(int v) { value=v; } void setValue(int v) {value=v; } int getValue() const { return value; } private: int value; }; class Interface Interface(int); void setValue(int); int getValue() const; Implementation *ptr;
6
Interface::Interface(int v) : ptr(new Implementation(v)) {}
void Interface::setValue(int v) { ptr->setValue(v); } int Interface::getValue() const { return ptr->getValue(); } int main() { Interface i(5); cout<<“Interface contains: “<<i.getValue() <<“ before setValue”<<endl; i.setValue(10); <<“ after setValue”<<endl; return 0; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.