CS201-26 - Introduction to Programming Lecture 26 Today’s...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Introduction to Programming Lecture 26 Today’s Lecture – Classes – Object struct Class A class has – data – functions Class A Class is a user defined data type. Object The instances of the class are called Objects. Structure of a class class name_of_class { // definition of a class } struct Date { int day ; int month ; int year ; } ; Example 1 Date mydate ; mydate.month = 1 ; mydate.day = 21 ; mydate.year = 1979 ; class Date { int day ; int month ; int year ; } ; Example 2 Example 2 main ( ) { Date mydate ; /* manipulate the data members mydate.day ; mydate.month ; mydate.year ; */ } class Date { int day ; int month ; int year ; } ; Example 2 Example 2 main ( ) { Date mydate; mydate.month = 10 ; // Error } Private Default visibility of all data and function inside a class is private Public class Date { private : // private data and functions public : }; // public data and functions class Date { int day ; int month ; int year ; } ; Date Class main ( ) { Date mydate ; mydate.month = 10 ; // illegal } class Date { private : int day , month , year ; public : setMonth ( ) ; print ( ) ; }; Date Class main ( ) { Date mydate ; mydate.setMonth ( 10 ) ; mydate.print ( ) ; } Separation of Interface from the Implementation. class Date { public : private: } ; Example 3 void display ( ) ; Date ( int day , int month , int year ) ; int day , month , year ; Example 3 void Date :: display ( ) { cout << day << “/ " << month << “/ " << year ; } Scope Resolution Operator Example 3 main ( ) { Date mydate ; mydate.display ( ) ; } Example 3: Modified class Date { public : Date ( int month , int day , int year ) ; void display ( ) ; setDay ( int ) ; setMonth ( int ) ; setYear ( int ) ; int month , day , year ; private : } ; main ( ) { Date mydate ; mydate.setDay ( 10 ) ; } Example 3: Modified Example 3: Modified void Date :: setDay ( int i ) { day = i ; } main ( ) { Date date1 , date2 , date3 ; date1.setMonth ( 10 ) ; date2.display ( ) ; } Example 3: Modified Constructor Example 3: Modified class Date { public : Date ( int month , int day , int year ) ; void display ( ) ; private : int month , day , year ; }; Date :: Date ( int month , int day , int year ) { // Body of the function } Example 3: Modified main ( ) { Date mydate ( 1 , 1 ,2002 ) ; mydate.display ( ) ; } Date :: Date ( int day , int month , int year = 2002 ) main ( ) { Date mydate ( 1 , 1 ,2002 ) ; Date mydate ( 1 , 1 ) ; } Example 3: Modified ...
View Full Document

This note was uploaded on 01/12/2010 for the course CS CS 201 taught by Professor Dr.naveedmalik during the Spring '09 term at Virtual University of Pakistan.

Ask a homework question - tutors are online