© 2009 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu
HomeSource Code Network Simulator ► Wireless▼
Otcl coding to create classes and objects.

Description:

      An OTcl script that defines two object classes, "teacher" and "student", where "Student" is the child class of "teacher", and a member function called "greet" for each class. After the class definitions, each object instance is declared, the "subject" variable of each instance is set to maths for teacher and name for student and the "greet" member function of each object instance is called. The keyword Class is to create an object class and instproc is to define a member function to an object class. Class inheritance is specified using the keyword -superclass. In defining member functions, $self acts same as the "this" pointer in C++, and instvar checks if the following variable name is already declared in its class or in its superclass. Finally, to create an object instance, the keyword new is used.

File name: “Otcl.tcl”

# Add a member function call”greet”
Class Teacher
Teacher instproc init {subject} {
$self instvar subject_
set subject_ $subject
}
# Creating a child class of teacher and student
Teacher instproc greet {} {
$self instvar subject_
puts "$subject_ teacher ask
which subject u studied?"
}
#creating a teacher and student object
Class student -superclass Teacher
student instproc greet {} {
$self instvar subject_
puts "$subject_ say
i studied maths"
}
# calling member function “greet” of each node
set a [new Teacher maths]
set b [new student Jey]
$a greet
$b greet

#how to run
$ns <filename>.tcl

# output snapshot

 


bottom