cs32w09dis3 - CS32 Introduction to Computer Science II...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Discussion 3A Notes (Week 4, January 30) TA: Brian Choi ([email protected]) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Inheritance Basics Inheritance in C++ refers to the process of deriving a new class using another class as a base . The old class used as a base is called the base class and the new class is called the derived class . In other contexts they may be called the parent class and the child class . Let’s do an example: class Dog : public Animal ” indicates that Dog inherits Animal . All members (both functions and variables) of Animal are also members of Dog , but not vice versa. Here is an example of using these classes: Dog d1; d1.setName(“puppy”); d1.setAge(1); // from Animal d1.speak(); // from Animal Animal a1; a1.setAge(2); //a1.setName(“10”); // error! 1. The derived class inherits all member functions of the base class except the assignment operator ( operator= ), constructors, and the destructor. 2. The derived class cannot access the private members of the base class directly. ( Dog cannot access m_age directly, although it is part of its member.) 3. When we say class D : public B , we mean “a D object is a kind of B .” This means you should not use public inheritance if such relationship does not hold. Take a look at the description of “ is-a relationship” in the textbook (p. 396). 4. As always, data members should always be private. CS32: Introduction to Computer Science II Winter 2009 Week 4, Page 1/5 class Animal { public: Animal(); ~Animal(); int getAge() const; void setAge(int age); void speak() const; private: int m_age; }; class Dog : public Animal { public: Dog(); ~Dog(); string getName() const; void setName(string name); private: string m_name; }; setName(), getName() m_name getAge(), setAge(), speak() m_age Animal Dog
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Construction/Destruction Dog objects are Animal objects. Therefore, when we create a Dog object, we’re also creating an Animal object. So when an instance of Dog is created, the Animal constructor is called to create an Animal first, and then the Dog constructor is called to complete the construction of a Dog . More generally, when an object is created:
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 5

cs32w09dis3 - CS32 Introduction to Computer Science II...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online